package com.tg.app.activity.device;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.tg.app.activity.base.DeviceListBaseActivity.OPEN_DRIVE_LOCAL_PALYBACK_SDCARD;
import static com.tg.app.camera.Camera.CONNECTION_STATE_SESSION_CLOSED_TIMEOUT;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSON;
import com.appbase.custom.app.AppStatusChangeListener;
import com.appbase.custom.app.STATUS;
import com.appbase.custom.config.TGConfig;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.appbase.custom.constant.LensesConstants;
import com.demo.helper.BatteryHelper;
import com.demo.view.RecordAudioView;
import com.demo.view.TGFocusingView;
import com.demo.view.ViewAnimFactory;
import com.magicindicator.buildins.UIUtil;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.NetworkUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.base.toolkit.WifiAp;
import com.tange.core.backend.service.http.ClientObserver;
import com.tange.core.data.structure.Device;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tange.module.core.wifi.scan.BizWiFiUtil;
import com.tange.module.core.wifi.scan.WiFiScanManager;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.socket.SocketIoConstants;
import com.tange.xbanner.XBanner;
import com.tg.app.R;
import com.tg.app.activity.base.CameraBaseActivity;
import com.tg.app.activity.base.DeviceListBaseActivity;
import com.tg.app.activity.device.add.LocationGrantGuideActivity;
import com.tg.app.activity.device.ui.cameraview.CameraLiveFragment;
import com.tg.app.activity.device.ui.cameraview.CameraLiveViewFragment;
import com.tg.app.activity.device.ui.cameraview.CarLiveFragment;
import com.tg.app.activity.device.ui.cameraview.PlayBackBaseFragment;
import com.tg.app.activity.device.ui.cameraview.SdCardPlayBackFragment;
import com.tg.app.activity.tools.DevToolsActivity;
import com.tg.app.adapter.PrePositionDialogAdapter;
import com.tg.app.bean.DevicePresetPoints;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.camera.CameraHelper;
import com.tg.app.camera.OnSpeakCommandCallback;
import com.tg.app.camera.P2PReport;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.CameraBottomSheetDialogHelper;
import com.tg.app.helper.CameraViewHelper;
import com.tg.app.helper.CarWatchTimeHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.helper.DeviceFunHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.MultiPlayerHelper;
import com.tg.app.helper.ServiceInfoHelper;
import com.tg.app.helper.TGGlobalConfigHelper;
import com.tg.app.helper.WiFiUtilWrapper;
import com.tg.app.listener.OnCameraZoomListener;
import com.tg.app.listener.OnZoomViewListener;
import com.tg.app.statistics.TangeVideoPlayStatistics;
import com.tg.app.util.LocalVideoDataUtil;
import com.tg.app.util.LogUtils;
import com.tg.app.util.UriUtil;
import com.tg.app.view.ACCameraPlayerView;
import com.tg.app.view.ACCameraShowErrorView;
import com.tg.app.view.CameraPlayerPiPView;
import com.tg.app.view.CameraPlayerStatusView;
import com.tg.app.view.CameraPlayerToolbarView;
import com.tg.app.view.CameraPlayerView;
import com.tg.app.widget.BottomSheetListDialog;
import com.tg.app.widget.PrePositionDialog;
import com.tg.app.widget.PtzControlDialog;
import com.tg.app.widget.PtzControlView;
import com.tg.app.widget.ZoomView;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.app.AppStatusObserver;
import com.tg.data.bean.DeviceItem;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.data.http.entity.AVFrames;
import com.tg.data.http.entity.DeviceServiceStatusBean;
import com.tg.data.http.entity.WatchTime;
import com.tg.data.media.AudioRecorder;
import com.tg.data.media.OnICameraAVListener;
import com.tg.data.media.OnICameraListener;
import com.tg.data.media.OnICameraRecordListener;
import com.tg.data.media.OnMediaFormatChangedListener;
import com.tg.data.media.OnMediaPlayListener;
import com.tg.data.media.OnScreencapListener;
import com.tg.data.media.VideoDecoder;
import com.tg.network.socket.http.TGHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


public class CameraViewActivity extends CameraBaseActivity implements OnICameraAVListener, OnICameraListener,OnCameraZoomListener, ACCameraPlayerView.ACCameraPlayerViewClickListener {
    private static final String TAG = CameraViewActivity.class.getSimpleName();
    protected ACCameraPlayerView mPlayerView;
    private static final String CUSTOMER_LOG = "CustomerService";
    private static final String LAMP_DEVICE_TIP = "lamp_device_tip";
    private static final String PRE_POSITION = "pre_position";
    public static final String ZOOM_DEFAULT = "zoom_default";
    public static final String ZOOM_INIT = "zoom_init";
    public static final int EVENT_PLAY_TOOBAR_HIDE = 0x01;
    public static final int EVENT_SEND_PTZCMD_LONG = 0x02;
    public static final int EVENT_ZOOM_HIDE = 0x03;
    public static final int EVENT_PLAYER_ZOOM = 0x04;
    public static final int EVENT_THUMB_HIDE = 0x05;
    public static final int EVENT_PLAY_RECONNECTED = 0x07;
    public static final int EVENT_PTZCMD_HIDE = 0x08;
    public static final int EVENT_BITRATE = 0x09;
    public static final int EVENT_DEVICE_INFO = 0x0a;
    public static final int EVENT_DEVICE_INFO_HIDE = 0x0B;
    public static final int EVENT_SESSION_TIME_OUT = 0x0C;
    public static final int EVENT_FRAME_RATE = 0x0D;
    public static final int EVENT_SEND_FOCUSCMD_LONG = 0x0E;
    public static final int PLAY_MODE_REALTIME = 0;
    public static final int PLAY_MODE_BACK_CLOUD = 1;
    private static final int PLAY_MODE_BACK_SDCARD = 2;
    public boolean mIsUserOffline;
    public FrameLayout mFlContainer;
    public RelativeLayout relCameraView, relToolbar;
    private boolean isMuteOn;
    private boolean isSaveing;
    private TextView deviceNameText;
    private CameraLiveViewFragment mLiveViewFragment;
    private PlayBackBaseFragment mPlayBackFragment;

    private boolean connectCallBefore = false;
    private boolean startShowCallBefore = false;
    private boolean recviceVideoDataCallBefore = false;
    private boolean recviceVideoFormatCallBefore = false;

    private boolean recviceVideoDataCloudCallBefore = false;
    private boolean recviceVideoDataCardCallBefore = false;
    private boolean recviceVideoDataCardOutsideCallBefore = false;

    private boolean isLandscape = false;
    private TextView btnSettings;
    private int difHeight = 190;
    private int animatedHeight = 0;
    public static final long HIDE_TIME = 5000;
    private DeviceBroadCastReceiver receiver;
    private String jumpTime;
    private boolean isPlayToobarShow = false;
    private boolean reConnected = false;
    private int reConnectedCount = 0;
    private final static int MAX_RECONNECT_COUNT = 5;
    private Runnable sleepRunnable;
    private boolean isGetEnv = false;
    private boolean mIsPlayBackRunning;

    private int playHeight = 0;
    private volatile int videoSize = 0;
    private volatile int frameRate = 0;
    private boolean isPlayStatusInfo = true;
    private int channel = 0;
    private int playType = 0;
    private boolean isZoomBarChanged;
    private ACCameraShowErrorView mCameraPlayerShowErrorView;
    private AudioRecorder audioRecorder;
    private OnICameraRecordListener onICameraRecordListener;
    private PtzControlView.OnPtzControlTouchListener ptzControlTouchListener;
    private TGFocusingView.OnFocusTouchListener onFocusTouchListener;
    private WatchTime watchTime;
    private long startLiveTime;
    private boolean isPlaybackPause;
    private LocalVideoDataUtil localVideoDataUtil;
    private boolean isLocationGranted;
    protected TGAlertDialog floatingWindowDialog;
    private final DeviceFunHelper deviceFunHelper = new DeviceFunHelper();
    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what) {
                case EVENT_SEND_PTZCMD_LONG:
                    TGLog.d(PtzControlView.TAG, "EVENT_SEND_PTZCMD_LONG" + isLiveFragmentVisiable());
                    if (isLiveFragmentVisiable()) {
                        mLiveViewFragment.setSendPTZCmd(true);
                    }

                    if (prePositionHelper != null){
                        prePositionHelper.setSendPTZCmd(true);
                    }
                    mPlayerView.setSendPTZCmd(true);
                    if (mCamera != null) {
                        mCamera.sendPTZCMD(message.arg1, channel);
                    }
                    break;
                case EVENT_SEND_FOCUSCMD_LONG:

                    mPlayerView.setSendFoucsCmd(true);
                    if (mCamera != null) {
                        mCamera.sendPTZCMD(message.arg1, channel);
                    }

                    break;
                case EVENT_ZOOM_HIDE:
                    mPlayerView.setZoomHidden();
                    break;
                case EVENT_PLAYER_ZOOM:
                    relCameraView.getLayoutParams().height = message.arg1;
                    relCameraView.requestLayout();
                    break;
                case EVENT_PLAY_TOOBAR_HIDE:
                    TGLog.i(TAG, "toolbar_hide");
                    mPlayerView.setToolbarVisibility(View.INVISIBLE);
                    if (mPlayerView.getPlayerStatus() == CameraPlayerStatusView.STATUS_NONE) {
                        setToolbarVisibility(View.INVISIBLE);
                    }
                    break;
                case EVENT_THUMB_HIDE:
                    mPlayerView.hideThumbnail();
                    break;
                case EVENT_SESSION_TIME_OUT:
                    autoCameraLoading();
                    break;
                case EVENT_PLAY_RECONNECTED:
                    TGLog.d("TGLoading", "reConnectedCount = " + reConnectedCount);
                    if (reConnectedCount < MAX_RECONNECT_COUNT) {
                        connect();
                    } else {
                        cameraDisconnect();
                    }
                    reConnectedCount++;
                    TGLog.d(" Cs2Camera reConnectedCount: " + reConnectedCount);
                    break;
                case EVENT_PTZCMD_HIDE:
                    mPlayerView.ptzDirectionHide();
                    break;
                case EVENT_FRAME_RATE:
                    mPlayerView.updateFrameRate(frameRate);
                    frameRate = 0;
                    mHandler.removeMessages(EVENT_FRAME_RATE);
                    mHandler.sendEmptyMessageDelayed(EVENT_FRAME_RATE, 1000);
                    break;
                case EVENT_BITRATE:
                    float bitrate = 8 * videoSize / 1024.0f;
                    videoSize = 0;
                    mPlayerView.updateBitrate(bitrate);
                    mHandler.sendEmptyMessageDelayed(EVENT_BITRATE, 1000);
                    break;
                case EVENT_DEVICE_INFO:
                    getDeviceStatusInfo();
                    break;
                case EVENT_DEVICE_INFO_HIDE:
                    mPlayerView.updateBatteryImageStatus(-1, -1, -1);
                    break;
            }

            return false;
        }
    });

    public ACCameraPlayerView getPlayerView() {
        return mPlayerView;
    }

    private void showBanner(){
        DeviceFunHelper.EntryBean data = new DeviceFunHelper.EntryBean();
        data.setTitle("Fullscreen,Clarity,Sound,Record Screen");
        deviceFunHelper.addData(data);

        DeviceFunHelper.EntryBean data1 = new DeviceFunHelper.EntryBean();
        data1.setTitle("Screen shot");
        deviceFunHelper.addData(data1);

        TGThreadPool.executeOnUiThread(() -> {
            deviceFunHelper.refreshTools();
            deviceFunHelper.initBanner(CameraViewActivity.this);
            deviceFunHelper.showBanner(true);
        });

    }


    private void getParames(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            jumpTime = getIntent().getStringExtra(CommonConstants.EXT_JUMP_EVENT_TIME);
            if (isCloudType() || mOrigin == DeviceListBaseActivity.PUSH_TARGET_PALYBACK_SDCARD || mOrigin == OPEN_DRIVE_LOCAL_PALYBACK_SDCARD) {
                mIsPlayBackRunning = true;
                mPlayerView.setPlaybackRunning(true);
                mDeviceUIHelper.setPlaybackDisplay(isCloudType() ? PLAY_MODE_BACK_CLOUD : PLAY_MODE_BACK_SDCARD);

                initPlayback(isCloudType() ? CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD : CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD, true, getFrom());
                if (mOrigin == DeviceListBaseActivity.PUSH_TARGET_PALYBACK_SDCARD || mOrigin == OPEN_DRIVE_LOCAL_PALYBACK_SDCARD) {
                    mDeviceUIHelper.setPlaybackDisplay(PLAY_MODE_BACK_SDCARD);
                } else {
                    mDeviceUIHelper.setPlaybackDisplay(PLAY_MODE_BACK_CLOUD);
                }
                mPlayerView.setCameraType(CommonConstants.CAMERA_TYPE_LIVE);
                mPlayerView.setLiveViewShow(false);

                int height = (int) getResources().getDimension(R.dimen.player_height) + DimenUtil.dp2px(this, 50);
                if (CameraViewHelper.supportMultiChannelsPlaybackVertical(mDeviceFeature,this)){
                    height = CameraViewHelper.getPlaybackHeight(mDeviceFeature,this);
                }
                setCameraViewHeight(height);
                getSupportFragmentManager().beginTransaction().replace(R.id.camera_view_container, mPlayBackFragment).commitNow();
                if (DeviceHelper.isCar(mDevice)) {
                    if (isCloudType()) {

                    } else {
                        mOrigin = DeviceListActivity.OPEN_DRIVE_LOCAL;

                        if (mCamera != null) {
                            mCamera.enableLanSearch();
                        }
                    }
                }
            } else {
                mDeviceUIHelper.setPlaybackDisplay(PLAY_MODE_REALTIME);
                if (mOrigin == DeviceListActivity.OPEN_DRIVE_LOCAL) {


                    if (mCamera != null) {
                        mCamera.enableLanSearch();
                    }
                } else {
                    if (!CameraHub.getInstance().isEnableLocalApConnect() && mDevice != null && mCamera != null) {
                        mCamera.disableLanSearch(mDevice.password);
                    }
                    if (DeviceHelper.isCar(mDevice)) {
                        TGLog.i(TAG, "setResolutionHide");
                        mPlayerView.setResolutionHide(true);

                    }
                }
                initLive();
                if (DeviceHelper.isGPSCar(mDevice) && !isLocalConnect()) {
                    int height = (int) getResources().getDimension(R.dimen.player_height) + DimenUtil.dp2px(this, 50);
                    if (!DeviceFeatureHelper.supportSpeaker(mDeviceFeature)){
                        height += DimenUtil.dp2px(this, 70);
                    }
                    setCameraViewHeight(height);
                } else {
                    setCameraViewHeight(playHeight);
                }
                getSupportFragmentManager().beginTransaction().replace(R.id.camera_view_container, mLiveViewFragment).commitNow();
                showOpenServe();
            }

            mPlayerView.setPlaybackRunning(mIsPlayBackRunning);

        }
    }


    private boolean isCloudType() {
        return mOrigin == DeviceListBaseActivity.PUSH_TARGET_PALYBACK_CLOUD;
    }

    private void queryCarWatchTime() {
        if (DeviceHelper.isCarPrimary(mDevice)) {
            CarWatchTimeHelper.watchTimeQuery(mDevice.uuid, time -> {
                watchTime = time;
                if (time == null) {
                    mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_NETWORK_ERROR);
                    return;
                }
                if (!CarWatchTimeHelper.isCarPrimaryWatchEnd(time)) {
                    if (mCamera.isConnected()) {
                        startLive();
                    } else {
                        connect();
                    }
                } else {
                    isCanDo();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        P2PReport.isPlayerStart = false;
        requestLocalPermission();
        buildAudioRecorder();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(getLayoutResID());
        hideActionBar();
        initView();
        setHeight();
        getParames(savedInstanceState);
        setListener();
        AppStatusObserver.getInstance().registerListener(mAppStatusChangeListener);
        //设置行车记录仪服务器的错误提示
        setErrorMessage();
        setPlayerView();
        registerReceiver();
        printDeviceLog();

        String token = PreferenceUtil.getString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_TOKEN);
        TGLog.d(TAG,"web token :"+token);
        TGLog.i(TAG, "onCreate done");
    }

    private void requestLocalPermission() {
        if (isLocalConnect()){
            isLocationGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            if (!isLocationGranted) {
                LocationGrantGuideActivity.launch(this);
            }
        }
    }

    private void printDeviceLog() {
        if (mCamera != null && deviceSettingsInfo != null) {
            TGLog.i(TAG, "Camera === " + mCamera.deviceName + "connectionState = " + mCamera.connectionState + ", deviceSettingsInfo.zoomPos = " + deviceSettingsInfo.zoomPos);
        }
    }

    private void hidePlayerInfoView(){
        if (mCamera != null && !mCamera.isConnected()){
            mPlayerView.hidePlayTopInfoView(mCamera.uid);
        }
    }
    private void setPlayerView() {
        if (mDevice != null) {
            mPlayerView.setDeviceItem(mDevice);
        }
        mPlayerView.setDeviceFeature(mDeviceFeature);
        hidePlayerInfoView();
        mPlayerView.setOnCameraZoomListener(this);

        updateZoomInfo();

    }

    private void updateZoomInfo() {
        if (deviceSettingsInfo != null) {
            deviceSettingsInfo.zoomPos = DeviceFeatureHelper.analogZoom(mDeviceFeature, deviceSettingsInfo.zoomPos);
            if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)){
                TGLog.d("deviceSettingsInfo.zoomPos = " + deviceSettingsInfo.zoomPos + ", deviceSettingsInfo.zoomPos2 = " + deviceSettingsInfo.zoomPos2);
                deviceSettingsInfo.zoomPos2 = DeviceFeatureHelper.analogZoom(mDeviceFeature, deviceSettingsInfo.zoomPos2);
                mPlayerView.updateZoomLenses(deviceSettingsInfo.zoomPos, 0);
                mPlayerView.updateZoomLenses(deviceSettingsInfo.zoomPos2, 1);
            }else{
                mPlayerView.updateZoomLenses(deviceSettingsInfo.zoomPos, 0);
            }
            mPlayerView.initZoomLenses();
        }
    }


        private void buildAudioRecorder() {
        if (audioRecorder == null) {
            audioRecorder = AudioRecorder.getInstance();
        }else {
            audioRecorder.release();
        }
        boolean supportTalkBack = CameraViewHelper.isTalkback2W(getBaseContext());
        if (supportTalkBack){
                audioRecorder.createDefaultAudio();
        }
            Log.d("Audio","buildAudioRecorder init");

    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SocketIoConstants.NOTIFY_DEVICE_STATUS);
        filter.addAction(CommonConstants.ACTION_INTENT_USER_OFFLINE);
        // 监视蓝牙关闭和打开的状态
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        // 监视蓝牙设备与APP连接的状态
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);

        receiver = new DeviceBroadCastReceiver();
        registerReceiver(receiver, filter);
    }

    private void setCameraViewHeight(int height) {
        ConstraintLayout.LayoutParams cameraViewLayoutParams = (ConstraintLayout.LayoutParams) relCameraView.getLayoutParams();
        cameraViewLayoutParams.width = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT;
        cameraViewLayoutParams.height = height;
        mPlayerView.setCameraViewSize(cameraViewLayoutParams.height);
        relCameraView.setLayoutParams(cameraViewLayoutParams);
    }

    private void setErrorMessage() {
        if (CameraHub.getInstance().isEnableLocalApConnect()) return;
        if (DeviceHelper.isDeviceForeignIccid(mDevice)) {
            setDeviceForeignIccId();
            return;
        }
        if (DeviceHelper.isCar(mDevice)) {
            if (mCameraPlayerShowErrorView != null) {
                mCameraPlayerShowErrorView.setCarErrorInfo();
            }
        } else if (DeviceHelper.is4GDevice(mDevice)) {
            if (mCameraPlayerShowErrorView != null) {
                mCameraPlayerShowErrorView.setText(getString(R.string.sim_service_expired));
                mCameraPlayerShowErrorView.setButtonText(getString(R.string.extended_use));
            }
        }
    }

    private void setDeviceForeignIccId() {
        runOnUiThread(() -> {
            mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_FOREIGN_ICC_ID_NOTICE);
            mPlayerView.setErrorText(mDevice.foreign_iccid_notice);
        });

    }


    public boolean isMicrophoneClose() {
        TGLog.d("CameraViewActivity",  "mIsPlayblackRunning = " + mIsPlayBackRunning);

        TGLog.d("CameraViewActivity",  "mDeviceFeature = " + mDeviceFeature);

        if (!mIsPlayBackRunning && mDeviceFeature != null) {
            TGLog.d("CameraViewActivity",  "supportMicrophone = " + mDeviceFeature.supportMicrophone);
            TGLog.d("CameraViewActivity",  "supportMicrophoneTune = " + mDeviceFeature.supportMicrophoneTune);
            TGLog.d("CameraViewActivity",  "supportMicrophoneMuteable = " + mDeviceFeature.supportMicrophoneMuteable);
            TGLog.d("CameraViewActivity",  "deviceSettingsInfo = " + deviceSettingsInfo);
            if (mDeviceFeature.supportMicrophone || mDeviceFeature.supportMicrophoneTune || mDeviceFeature.supportMicrophoneMuteable){
                if (deviceSettingsInfo != null){
                    TGLog.d("CameraViewActivity",  "deviceSettingsInfo.microphoneOn = " + deviceSettingsInfo.microphoneOn);
                }
                if (deviceSettingsInfo != null && deviceSettingsInfo.microphoneOn == 0 && !StringUtils.isEmpty(mDeviceFeature.microphoneInfo)) {
                    isMuteOn = true;
                    mPlayerView.setMuteOn(true);
                    mCamera.stopAudio();
                    return true;
                }
            }
        }

        TGLog.d("CameraViewActivity",  "deviceSettingsInfo.false");
        return false;
    }

    private void showOpenServe() {
        if (isLocalConnect()) return;
        if (DeviceHelper.isDeviceForeignIccid(mDevice)) {
            setDeviceForeignIccId();
            return;
        }
        if (DeviceHelper.isCar(mDevice) && DeviceHelper.getCarServer(mDevice) == null) {
            mCameraPlayerShowErrorView.setVisibility(View.VISIBLE);
        }
    }

    private void setHeight() {
        playHeight = getPlayHeight();
        difHeight = (int) (playHeight - getResources().getDimension(R.dimen.player_height) - DimenUtil.dp2px(this, 50));
        TGLog.d("difHeight = " + difHeight);
    }

    private final PtzControlView.OnPtzControlTouchListener mOnPtzControlTouchListener = new PtzControlView.OnPtzControlTouchListener() {
        @Override
        public void onShortCmd(int control) {
            TGLog.i(TAG, "Ptz onShortCmd false");
            onPtzShortCmd(control, false);
        }

        @Override
        public void onStopCmd() {
            TGLog.i(TAG, "Ptz onStopCmd false");
            onPtzStopCmd();
        }

        @Override
        public void onLongCmd(int control) {
            TGLog.d(PtzControlView.TAG, "Ptz onLongCmd");
            onPtzLongCmd(control, false);
        }
    };


    private void initLive() {
        if (DeviceHelper.isGPSCar(mDevice) && !isLocalConnect()) {
            mLiveViewFragment = CarLiveFragment.newInstance(mDeviceFeature, mDevice);
            if (DeviceHelper.isCar(mDevice)) {
                mPlayerView.setResolutionHide(true);
                queryCarWatchTime();
            }
        } else {
            CameraLiveFragment cameraLiveFragment = CameraLiveFragment.newInstance(mDeviceFeature, mDevice);
            cameraLiveFragment.setOnPtzControlTouchListener(mOnPtzControlTouchListener);
            cameraLiveFragment.setCamera(mCamera);
            mLiveViewFragment = cameraLiveFragment;
        }
        getPlayerView().setOnControlClickListener(null);
        isPlaybackPause = false;
        setCameraListener();
        mPlayerView.setCameraType(CommonConstants.CAMERA_TYPE_LIVE);

        setSpeed(1);
        mLiveViewFragment.setRecordAudioListener(new RecordAudioView.IRecordAudioListener() {
            @Override
            public void onRecordStart() {
                uploadLog("onSpeaking");
                startAudioRecoder();
                mPlayerView.audioReset();
                boolean supportTalkBack = CameraViewHelper.isTalkback2W(getBaseContext());
                if (!supportTalkBack){
                    mPlayerView.setMuteEnable(false);
                }
            }

            @Override
            public void onRecordStop() {
                boolean supportTalkBack = CameraViewHelper.isTalkback2W(getBaseContext());
                if (!supportTalkBack){
                    mPlayerView.setMuteEnable(true);
                }
                stopAudioRecorder();
            }
        });
        mIsPlayBackRunning = false;
        mPlayerView.setPlaybackRunning(false);
        TGLog.d("mIsPlayblackRunning >> " + JSON.toJSONString(mIsPlayBackRunning));
        onICameraRecordListener = data -> {
            if (mCamera != null && mCamera.isConnected()) {
                mCamera.sendAudioData(data);
                runOnUiThread(() -> {
                    if (mLiveViewFragment != null && !isLandscape) {
                        short f = AudioRecorder.calculateVolume(data);
                        mLiveViewFragment.calculateVolume(f);
                    }
                    requestDeviceSleep();
                });
            }
        };
    }
    private void setCameraListener(){
        if (mLiveViewFragment!=null){
            mLiveViewFragment.setOnICameraAVListener(this);
            mLiveViewFragment.setCameraListener();
        }else if (mPlayBackFragment!=null){
            mPlayBackFragment.setOnICameraAVListener(this);
            mPlayBackFragment.setCameraListener();
        }
    }
    private void startAudioRecoder(){

         boolean supportTalkBack = DeviceFeatureHelper.isAec(mDeviceFeature);
        if (!supportTalkBack){
            mPlayerView.setMuteOn(true);
        }

        if (mCamera != null) {
            if (!supportTalkBack){
                mCamera.stopAudio();
            }
            mCamera.startSpeaking();
            mCamera.setOnSpeakCommandCallback(new OnSpeakCommandCallback() {
                @Override
                public void onNotAllowed() {
                    // 对讲通道被占用时提示
                    TGThreadPool.executeOnUiThread(() -> {
                        TGToast.showLongToast(CameraViewActivity.this, getString(R.string.can_not_talk_because_other_people));
                        if (mLiveViewFragment != null) {
                            mLiveViewFragment.onRecordStop();
                        }
                    });
                }

                @Override
                public void onSuccess() {

                }
            });
        }
        if (audioRecorder != null) {
            boolean isNoReady = audioRecorder.getStatus() == AudioRecorder.Status.STATUS_NO_READY;
            boolean isPause = audioRecorder.getStatus() == AudioRecorder.Status.STATUS_PAUSE;
            boolean isReady = audioRecorder.getStatus() == AudioRecorder.Status.STATUS_READY;
            if (isNoReady||isPause||isReady){
                if (isNoReady){
                    audioRecorder.createDefaultAudio(supportTalkBack);
                }
                if (onICameraRecordListener != null) {
                    audioRecorder.startRecord(onICameraRecordListener);
                }
            }
        }
    }
    private void stopAudioRecorder(){
        if (audioRecorder != null && audioRecorder.getStatus() == AudioRecorder.Status.STATUS_START) {
            audioRecorder.pauseRecord();
        }
        if (mCamera != null && mCamera.isConnected()) {
            mCamera.stopSpeaking();
        }
        boolean supportTalkBack = CameraViewHelper.isTalkback2W(getBaseContext());
        //开启了播放声音，需要重新打开
        if (!isMuteOn&&!supportTalkBack) {
            mPlayerView.setMuteOn(false);
            if (mCamera != null && mCamera.isConnected()) {
                mCamera.startAudio();
            }
        }
    }

    private void initPlayback(int pType, boolean isAnimationsStart, String from) {
        playType = pType;
        TGLog.d(TAG, "mPlaybackDisplay = " + mDeviceUIHelper.getPlaybackDisplay());
        mPlayBackFragment = ActivityHelper.newInstance(pType, mDevice, isAnimationsStart);
        setCameraListener();
        mPlayBackFragment.setDeviceItem(mDevice);
        showCameraViewContainer(true);
        getGetEnv();
        if (P2PReport.MESSAGE_DETAIL_PAGE.equals(from)) {
            mDeviceUIHelper.setIsScrolled(true);
        }
        mPlayBackFragment.setDeviceUIHelper(mDeviceUIHelper);
//        mPlayBackFragment.setPlaybackRunListener(new OnPlaybackRunListener() {
//            @Override
//            public void onPlaybackRun(boolean jump) {
//                TGLog.d(TAG, " setPlaybackRunListener mIsPlayblackRunning " + JSON.toJSONString(mIsPlayBackRunning) + "， jump = " + jump);
//                if (!mIsPlayBackRunning) {
//                    removeWatch2Report();
//                    reportPlayerInfo();
//                }
//                mIsPlayBackRunning = true;
//                TGThreadPool.executeOnUiThread(() -> mPlayerView.setPlaybackRunning(true));
//
//                TGLog.d(TAG, " setPlaybackRunListener mIsPlayblackRunning>>   " + JSON.toJSONString(mIsPlayBackRunning));
//                mHandler.removeMessages(EVENT_DEVICE_INFO);
//                mHandler.sendEmptyMessage(EVENT_DEVICE_INFO_HIDE);
//                playerViewRecordSave(jump);
//            }
//
//            @Override
//            public void onStopPlayback() {
//                mIsPlayBackRunning = false;
//                mPlayerView.setPlaybackRunning(false);
//                TGLog.d(TAG, " onStopPlayback mIsPlayblackRunning " + JSON.toJSONString(mIsPlayBackRunning));
//            }
//        });
        TGLog.d(TAG, "deviceSettingsInfo = " + deviceSettingsInfo);
        if (deviceSettingsInfo != null) {
            TGLog.d(TAG, "deviceSettingsInfo.total = " + deviceSettingsInfo.total);
        }

        if (deviceSettingsInfo != null) {
            if (!isAnimationsStart || deviceSettingsInfo.total != -999) {
                mPlayBackFragment.setSdCardSize(deviceSettingsInfo.total, false);
            }

            if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD && mIsPlayBackRunning && deviceSettingsInfo.total == 0) {
                Camera camera = CameraHub.getInstance().getCamera(mDevice.uuid);
                if (camera != null) {
                    camera.disconnect();
                }
            }
        }
        mPlayBackFragment.setJumpEventTime(jumpTime);
        jumpTime = null;
        setSpeed(Integer.parseInt(CameraPlayerToolbarView.SPEED_1));
        mPlayerView.showControlBtn(mIsPlayBackRunning);
    }





    @SuppressLint({"UseCompatLoadingForDrawables", "CutPasteId"})
    @Override
    protected void initView() {
        XBanner xBanner = findViewById(R.id.banner);
        deviceFunHelper.setBanner(xBanner);
        relToolbar = findViewById(R.id.rl_camera_view_toolbar);
        deviceNameText = findViewById(R.id.tv_camera_view_device_name);
        btnSettings = findViewById(R.id.btn_camera_view_settings);


        mPlayerView = findViewById(R.id.camera_view_player);
        mPlayerView.setDeviceUIHelper(mDeviceUIHelper);
        mPlayerView.setFloatView(relToolbar);
        mCameraPlayerShowErrorView = findViewById(R.id.ll_playback_view_cloud_service_none);

        mFlContainer = findViewById(R.id.camera_view_container);
        relCameraView = findViewById(R.id.rel_camera_view_layout);

        setClickListener();
        showBanner();

    }

    private void setClickListener() {
        mCameraPlayerShowErrorView.setButOnClickListener(v -> onOpenServe());
        btnSettings.setOnClickListener(v -> settingsClick());
        ImageButton btnBack = findViewById(R.id.btn_camera_view_back_toolbar);
        btnBack.setOnClickListener(v -> onBackPressed());
    }

    private void setListener() {
        mPlayerView.setPlayerViewClickListener(this);
        ptzControlTouchListener = new PtzControlView.OnPtzControlTouchListener() {
            @Override
            public void onShortCmd(int control) {
                TGLog.i(TAG, "Ptz onShortCmd true : " + control + ": ver = " + DeviceFeatureHelper.vertOnly(mDeviceFeature) + ", hor = " + DeviceFeatureHelper.horZOnly(mDeviceFeature));
                if (DeviceFeatureHelper.vertOnly(mDeviceFeature)){
                    if (control == AVIOCTRLDEFs.AVIOCTRL_PTZ_LEFT || control == AVIOCTRLDEFs.AVIOCTRL_PTZ_RIGHT){
                        return;
                    }
                }

                if (DeviceFeatureHelper.horZOnly(mDeviceFeature)){
                    if (control == AVIOCTRLDEFs.AVIOCTRL_PTZ_DOWN || control == AVIOCTRLDEFs.AVIOCTRL_PTZ_UP){
                        return;
                    }
                }

                if (control == AVIOCTRLDEFs.AVIOCTRL_PTZ_LEFT || control == AVIOCTRLDEFs.AVIOCTRL_PTZ_RIGHT || control == AVIOCTRLDEFs.AVIOCTRL_PTZ_DOWN || control == AVIOCTRLDEFs.AVIOCTRL_PTZ_UP){
                    onPtzShortCmd(control, true);
                }
            }

            @Override
            public void onStopCmd() {
                onPtzStopCmd();
                TGLog.i(TAG, "Ptz onStopCmd");
            }

            @Override
            public void onLongCmd(int control) {
                TGLog.i(TAG, "Ptz onLongCmd true : " + control + ": ver = " + DeviceFeatureHelper.vertOnly(mDeviceFeature) + ", hor = " + DeviceFeatureHelper.horZOnly(mDeviceFeature));
                if (DeviceFeatureHelper.vertOnly(mDeviceFeature)){
                    if (control == AVIOCTRLDEFs.AVIOCTRL_PTZ_LEFT || control == AVIOCTRLDEFs.AVIOCTRL_PTZ_RIGHT){
                        return;
                    }
                }

                if (DeviceFeatureHelper.horZOnly(mDeviceFeature)){
                    if (control == AVIOCTRLDEFs.AVIOCTRL_PTZ_DOWN || control == AVIOCTRLDEFs.AVIOCTRL_PTZ_UP){
                        return;
                    }
                }
                onPtzLongCmd(control, true);
            }
        };
        onFocusTouchListener = new TGFocusingView.OnFocusTouchListener() {
            @Override
            public void onShortCmd(int control) {
                TGLog.d(TAG, "onShortCmd control = " + control);
                if (mCamera != null) {
                    reToolbarHide();
                    CameraHelper.sendPTZCMDShort(mCamera, control, channel);
                }
            }

            @Override
            public void onStopCmd() {
                TGLog.i(TAG, "onStopCmd");
                onPtzStopCmd();
            }

            @Override
            public void onLongCmd(int control) {
                TGLog.d(TAG, "onLongCmd control = " + control);
                requestDeviceSleep();
                uploadLog("onPtzLongCmd");
                if (mCamera != null && mCamera.isConnected()) {
                    mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
                    mHandler.removeMessages(EVENT_PTZCMD_HIDE);
                    Message message = mHandler.obtainMessage();
                    message.what = EVENT_SEND_FOCUSCMD_LONG;
                    message.arg1 = control;
                    //5 毫秒后发
                    mHandler.sendMessageDelayed(message, 200);
                }


            }

            @Override
            public void onTouch(boolean up, boolean add) {
                if (up){
                    mPlayerView.hideZoomTextView(0);
                }else{
                    String text = ResourcesUtil.getString(R.string.focusing);
                    text += add? "+" : "-";
                    mPlayerView.setZoomTextView(text, 0);
                    reToolbarHide();
                }

            }
        };
        mPlayerView.setFocusTouchListener(onFocusTouchListener);
        mPlayerView.setOnPtzControlTouchListener(ptzControlTouchListener);
        mPlayerView.setOnMediaPlayListener(new OnMediaPlayListener() {
            @Override
            public void onMediaPlayFirstTimestamp(long pts) {
                TGLog.d("onMediaPlayFirstTimestamp pts = " + pts);
                mHandler.removeMessages(EVENT_FRAME_RATE);
                mHandler.sendEmptyMessageDelayed(EVENT_FRAME_RATE, 1000);
            }

            @Override
            public void onMediaPlayChanged(final boolean isStart) {
                if (isPlaybackFragmentVisible()) {
                    if (mPlayBackFragment != null) {
                        mPlayBackFragment.onMediaPlayChanged(isStart);
                    }
                }

                if (!isStart){
                    reportPlayerInfo();
                }
            }

            @Override
            public void onMediaPlayUpdated(final long pts) {
                TGLog.d("onMediaPlayUpdated pts = " + pts);
                frameRate++;
                if (isCanDo() || isLocalConnect()) {
                    if (mPlayerView.getLoadingVisibility() == VISIBLE) {
                        runOnUiThread(() -> {
                            mPlayerView.setLoadingVisibility(View.GONE);
                            mPlayerView.setSimServicePayBannerShow();
                        });
                    }
                    mPlayerView.updatePlaybackControl();
                    if (!CarWatchTimeHelper.isCarPrimaryWatchEnd(watchTime)) {
                        mPlayerView.setWatchTime(watchTime);
                    }
                    if (!isPlayToobarShow) {
                        runOnUiThread(() -> {
                            setToolbarVisibility(View.VISIBLE);
                            mPlayerView.setToolbarVisibility(View.VISIBLE);
                            TGLog.d("isPlayToobarShow ==== " + isPlayToobarShow);
                            isPlayToobarShow = true;
                            reToolbarHide();
                        });
                    }
                    if (pts != 0) {
                        if (isPlaybackFragmentVisible()) {
                            if (mPlayBackFragment != null) {
                                mPlayBackFragment.onMediaPlayUpdated(pts);
                            }
                        }
                        mPlayerView.audioSyncPts(pts);
                        if (startLiveTime == 0 && mCamera.isRunningLiveVideo()) {
                            requestWatchTime();
                        }
                    }

                }
            }


            @Override
            public void onMediaCloudPlayUpdated(final long pts) {
                if (isPlaybackFragmentVisible()) {
                    mPlayBackFragment.onMediaCloudPlayUpdated(pts);
                }
            }

        });

        mPlayerView.setOnScreencapListener(new OnScreencapListener() {
            @Override
            public void recordStart(boolean succeed) {
                isSaveing = succeed;
                reToolbarHide();
                if (succeed) {
                    mPlayerView.recordingUpdate(0);
                } else {
                    mPlayerView.screenSaveEnd();
                }

            }

            @Override
            public void recordEnd(boolean succeed) {
                if (succeed) {
                    showToast(getString(R.string.record_save));
                }
                isSaveing = false;
                mHandler.sendEmptyMessageDelayed(EVENT_THUMB_HIDE, 3000);
                runOnUiThread(() -> mPlayerView.screenSaveEnd());
                onScreenClick();
            }

            @Override
            public void recordingUpdate(final long duration) {
                if (isSaveing) {
                    runOnUiThread(() -> mPlayerView.recordingUpdate(duration));
                }
            }
        });
        mPlayerView.setOnZoomViewListener(new OnZoomViewListener() {
            @Override
            public void onSingleClick(boolean show) {
                long delay = 0;
                if (show){
                    delay = HIDE_TIME;
                    setToolbarVisibility(View.VISIBLE);
                    mPlayerView.setToolbarVisibility(View.VISIBLE);
                }else {
                    if (mCamera != null && mCamera.isConnected() || mPlayerView.getCameraType() == CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD) {

                        if (mPlayerView.getToolbarVisibility() != View.VISIBLE) {
                            mPlayerView.setToolbarVisibility(View.VISIBLE);
                            setToolbarVisibility(View.VISIBLE);
                            delay = HIDE_TIME;
                        }
                    } else if (mCamera != null && !mCamera.isConnected()) {
                        if (relToolbar.getVisibility() != View.VISIBLE) {
                            delay = HIDE_TIME;
                            setToolbarVisibility(View.VISIBLE);
                        }
                    }
                }

                TGLog.d("EVENT_PLAY_TOOBAR_HIDE7");
                mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
                mHandler.sendEmptyMessageDelayed(EVENT_PLAY_TOOBAR_HIDE, delay);
                onScreenClick();
            }

            @Override
            public void onScale(float scale) {
                mPlayerView.setUpdateViewSize(false);
                mHandler.removeMessages(EVENT_ZOOM_HIDE);
                mHandler.sendEmptyMessageDelayed(EVENT_ZOOM_HIDE, HIDE_TIME);
            }
        });
        mPlayerView.setOnPlayerForeSightListener((chn, x, y) -> {
            TGLog.i(TGLog.TAG,"onForeSightChanged x: "+x+" y:"+y);
            CameraHelper.setLocateInPicPoints(mCamera,chn,x,y);
        });
    }



    private void showPlaybackFragment(ViewGroup.LayoutParams layoutParams, int oldPlaybackDisplay, int pType, boolean animation) {
        mLiveViewFragment = null;
        initPlayback(pType, animation, P2PReport.DEVICE_LIST_PAGE);
        TGLog.d("relCameraView", "3 == height=" + layoutParams.height + ",w = " + layoutParams.width);
        if (oldPlaybackDisplay == 0 && animation) {
            getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.push_botton_in, R.anim.push_botton_out)
                    .replace(R.id.camera_view_container, mPlayBackFragment)
                    .commitNow();
            int playbackHeight = CameraViewHelper.getPlaybackHeight(mDeviceFeature, this);
            int curPlayerHeight = mPlayerView.getCurPlayerHeight() + DimenUtil.dp2px(this, 50);
            playbackHeight = Math.max(playbackHeight, curPlayerHeight);
            if (mPlayerView.getCurPlayerHeight() != 0){
                playbackHeight = curPlayerHeight;
            }
            mPlayerView.setCameraViewSize(playbackHeight);
            if (mDeviceFeature!=null){
                createValueAnimate(layoutParams.height, playbackHeight, 300, "click");
            }else{
                setCameraViewHeight(playbackHeight);
            }
        } else {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.camera_view_container, mPlayBackFragment)
                    .commitNow();
        }
        getPlayerView().setOnControlClickListener(pause ->  {
            isPlaybackPause = pause;
            mPlayBackFragment.playBackControl(pause);
        });

    }

    private boolean isToolbarMultiChannelsVisibile() {

        boolean isLiveShow = isLiveFragmentVisiable() && !isLandscape;
        boolean supportVertical = CameraViewHelper.supportMultiChannelsPlaybackVertical(mDeviceFeature,getBaseContext());
        isLiveShow = DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)&&!supportVertical && isLiveShow;
        return isLiveShow;
    }

    private void showLiveFragment(ViewGroup.LayoutParams layoutParams, boolean animation) {
        if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)) {
            mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
            setToolbarVisibility(View.VISIBLE);
            mPlayerView.setToolbarVisibility(View.VISIBLE);
        }
        mPlayBackFragment = null;
        initLive();
        TGLog.d("relCameraView", "2 == height=" + layoutParams.height + ",w = " + layoutParams.width + ", animation = " + animation);
        if (animation) {
            getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.push_botton_in, R.anim.push_botton_out).replace(R.id.camera_view_container, mLiveViewFragment).commitNow();
            playHeight = getPlayHeight();
            mPlayerView.setCameraViewSize(playHeight);
            createValueAnimate(layoutParams.height, playHeight, 300, "click");
        } else {
            getSupportFragmentManager().beginTransaction().replace(R.id.camera_view_container, mLiveViewFragment).commitNow();
        }
    }

    @Override
    public void setPtzControlViewVisible(boolean show) {
        if (AppUtil.isLandscape(CameraViewActivity.this)) {
            if (!show) {
                mFlContainer.setVisibility(View.GONE);
            }
            if (mLiveViewFragment != null) {
                mLiveViewFragment.setPtzControlViewVisible(show);
            }
        } else {
            if (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME) {
                boolean oldShow = show;
                if (mDeviceFeature != null && mDeviceFeature.support2Lenses && !mDeviceFeature.supportMultiChannels){
                    if (!show){
                        show = mDeviceFeature.supportPTZ || mDeviceFeature.supportPTZ2;
                    }
                    if (!show){
                        if (DeviceHelper.isLamp(mDevice)){
                            show = true;
                        }
                    }
                }else if (!show){
                    if (DeviceHelper.isLamp(mDevice)){
                        show = true;
                    }
                }
                if (show){
                    playHeight = getPlayHeight();
                }else{
                    playHeight = getNoPTZPlayHeight();
                }
                ViewGroup.LayoutParams layoutParams = relCameraView.getLayoutParams();
                boolean updateDeviceFeature = false;
                if (layoutParams.height != playHeight) {
                    mPlayerView.setCameraViewSize(playHeight);
                    createValueAnimate(layoutParams.height, playHeight, 100, "serve");
                }else if (mDeviceFeature != null && mDeviceFeature.support2Lenses && !mDeviceFeature.supportMultiChannels){
                    updateDeviceFeature = true;
                }

                if (mLiveViewFragment != null) {
                    mLiveViewFragment.setPtzControlViewVisible(oldShow);
                }

                if (updateDeviceFeature){
                    if (isPlaybackFragmentVisible()) {
                        if (CameraViewHelper.supportMultiChannelsPlaybackVertical(mDeviceFeature, getBaseContext())) {
                            mPlayerView.updateView();
                        }
                        mPlayBackFragment.addPlayBackFooterView();
                    }
                    if (isLiveFragmentVisiable()) {
                        mLiveViewFragment.updateDeviceFeature(mDeviceFeature);
                        if (!DeviceFeatureHelper.supportPTZ(mDeviceFeature) && !DeviceFeatureHelper.supportSpeaker(mDeviceFeature)){
                            showCameraViewContainer(false);
                        }
                        mPlayerView.updateView();
                    }

                }
            }
        }
    }

    @Override
    protected void updateLayout(boolean update) {
        super.updateLayout(update);
        if (update&&isPlaybackFragmentVisible()&&CameraViewHelper.supportMultiChannelsPlaybackVertical(mDeviceFeature,this)){
            int playbackHeight = CameraViewHelper.getPlaybackHeight(mDeviceFeature,this);
            setCameraViewHeight(playbackHeight);
        }
    }

    private void createValueAnimate(int start, int end, long duration, String from) {
        if (DeviceHelper.isGPSCar(mDevice) && !isLocalConnect()) return;

        final int end1 = end;
        TGLog.d("relCameraView","createValueAnimate start :" + start + " end: " + end + ", end1 = " + end1 + ", from = " + from);
        ViewAnimFactory viewAnimFactory = new ViewAnimFactory();
        viewAnimFactory.setView(relCameraView);
        ObjectAnimator animator = ObjectAnimator.ofInt(viewAnimFactory, "height", start, end1);
        animator.setDuration(duration);
        animator.addUpdateListener(valueAnimator -> animatedHeight = (Integer) valueAnimator.getAnimatedValue());
        mPlayerView.resetPlayerLocation();
        animator.addListener(new ValueAnimator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                animator.setupEndValues();
                if (animatedHeight != end1) {
                    createValueAnimate(animatedHeight, end1, 100, from);
                } else {
                    if (isPlaybackFragmentVisible()) {
                        if (CameraViewHelper.supportMultiChannelsPlaybackVertical(mDeviceFeature, getBaseContext())) {
                            mPlayerView.updateView();
                        }
                        mPlayBackFragment.addPlayBackFooterView();
                    }
                    if (isLiveFragmentVisiable()) {
                        mLiveViewFragment.updateDeviceFeature(mDeviceFeature);
                        if (!DeviceFeatureHelper.supportPTZ(mDeviceFeature) && !DeviceFeatureHelper.supportSpeaker(mDeviceFeature)){
                            showCameraViewContainer(false);
                        }
                        mPlayerView.updateView();
                    }

                }
            }

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onAnimationCancel(Animator animator) {
            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        animator.start();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mCamera != null) {
            TGLog.i("CameraLog", "this");
            mCamera.registerICameraListener(this);
        }

        TGLog.i(TAG, "CameraViewActivity  onResume");
        if (mCamera != null) {
            isPlayStatusInfo = PreferenceUtil.getBoolean(this, CommonConstants.PRE_SETTINGS_PICTURE_UUID + mCamera.uid, true);
            if (mDevice != null) {
                Camera localCamera = CameraHub.getInstance().getCamera(mDevice.uuid);
                if (localCamera != null && !TextUtils.isEmpty(localCamera.deviceName)) {
                    mCamera.deviceName = localCamera.deviceName;
                }
            }

            if (!TextUtils.isEmpty(mCamera.deviceName)) {
                deviceNameText.setText(mCamera.deviceName);
            }
            setSpeed(1);
            isMuteOn = PreferenceUtil.getBoolean(this, mCamera.deviceId + CommonConstants.EXT_MUTE_ON, true);
            if (!isMuteOn){
                if (mDeviceFeature != null && (mDeviceFeature.supportMicrophoneTune || mDeviceFeature.supportMicrophoneMuteable || mDeviceFeature.supportMicrophone)){
                    if (deviceSettingsInfo != null && deviceSettingsInfo.microphoneOn == 1){
                        isMuteOn = false;
                    } else if (deviceSettingsInfo != null && deviceSettingsInfo.microphoneOn == 0 && !StringUtils.isEmpty(mDeviceFeature.microphoneInfo)) {

                        isMuteOn = true;
                        PreferenceUtil.setBoolean(this, mCamera.deviceId + CommonConstants.EXT_MUTE_ON, true);
                    }
                }
            }

            mPlayerView.setMuteOn(isMuteOn);
            TGLog.d(TAG, "onResume isMuteOn = " + isMuteOn);
            if (isMuteOn) {
                mCamera.stopAudio();
            }else{
                mCamera.startAudio();
            }
        }

        if (mPlayerView != null){
            if (mPlayerView.swapScreen(mDeviceFeature)){
                updateZoomInfo();
            }
        }

        if (DeviceHelper.isSolar(mDevice)){
            if (mPlayerView != null){
                mPlayerView.setSolarDeviceRecordType();
            }
        }

        resume();
    }

    protected void resume() {
        setCameraListener();
        if (mCamera != null && mCamera.connectionState == Camera.CONNECTION_STATE_CONNECTED) {
            getGetEnv();
            if (!mCamera.isRunningLiveVideo()) {
                startLive();
                getPlayerView().mediaSyncStart();
            }
        } else {
            if (isLocalConnect()&&!isLocationGranted){
                return;
            }
            connect();
            hidePlayerInfoView();
        }


        showFloatingPermissionTips(CameraViewActivity.this, mDevice);
    }

    private void showFloatingPermissionTips(final Context context, final DeviceItem deviceItem) {
        if (!DeviceHelper.isLamp(deviceItem)){
            return;
        }

        if (context == null) return;
        int userId = PreferenceUtil.getInt(this, CommonConstants.PRE_USER_ID);
        boolean isShow = PreferenceUtil.getBoolean(context, deviceItem.uuid + LAMP_DEVICE_TIP + userId);
        if (!isShow){
            PreferenceUtil.setBoolean(context, deviceItem.uuid + LAMP_DEVICE_TIP + userId, true);
            TGThreadPool.executeOnUiThread(() -> {
                if (floatingWindowDialog != null && floatingWindowDialog.isShowing()) {
                    floatingWindowDialog.dismiss();
                }

                floatingWindowDialog = TGAlertDialog.openLampDialog(context,
                        v1 -> {
                            if (floatingWindowDialog != null && floatingWindowDialog.isShowing()) {
                                floatingWindowDialog.dismiss();
                            }
                        });
            });
        }
    }

    private void setupSurfaceView(int orientation) {
        isLandscape = orientation == Configuration.ORIENTATION_LANDSCAPE;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //横屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);


            btnSettings.setVisibility(GONE);

            adjustFullScreenView(mDeviceUIHelper.getPlaybackDisplay() != PLAY_MODE_REALTIME);
            mFlContainer.setVisibility(View.GONE);

            ConstraintLayout.LayoutParams cameraViewLayoutParams = (ConstraintLayout.LayoutParams) relCameraView.getLayoutParams();
            cameraViewLayoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
            cameraViewLayoutParams.width = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT;
            cameraViewLayoutParams.height = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT;
            relCameraView.setLayoutParams(cameraViewLayoutParams);

            RelativeLayout.LayoutParams mPlayerLayoutParams = (RelativeLayout.LayoutParams) mPlayerView.getLayoutParams();
            mPlayerLayoutParams.bottomMargin = 0;
            mPlayerView.setLayoutParams(mPlayerLayoutParams);
            mPlayerView.requestLayout();
            relToolbar.setPadding(DimenUtil.dp2px(this, 30), DimenUtil.dp2px(this, 10), DimenUtil.dp2px(this, 30), 0);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            ConstraintLayout.LayoutParams cameraViewLayoutParams = (ConstraintLayout.LayoutParams) relCameraView.getLayoutParams();
            cameraViewLayoutParams.bottomToBottom = -1;
            cameraViewLayoutParams.width = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT;
            relToolbar.setPadding(DimenUtil.dp2px(this, 10), DimenUtil.dp2px(this, 10), DimenUtil.dp2px(this, 10), 0);
            setHeight();

            if (isPlaybackFragmentVisible() && CameraViewHelper.supportMultiChannelsPlaybackVertical(mDeviceFeature, this)) {
                cameraViewLayoutParams.height = CameraViewHelper.getPlaybackHeight(mDeviceFeature, this);
            } else {
                int h450 = getPlayHeight();
                if (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME) {
                    cameraViewLayoutParams.height = h450;
                } else {
                    cameraViewLayoutParams.height = h450 - difHeight;
                    TGLog.d("CameraPlayerView","cameraViewLayoutParams.height111 " + cameraViewLayoutParams.height);
                    int playbackHeight = (int) getResources().getDimension(R.dimen.player_height);
                    VideoDecoder videoDecoder = getMediaSync();
                    if (videoDecoder != null && videoDecoder.getAlignWidth() != 0 && videoDecoder.getAlignHight() != 0){
                        playbackHeight = AppUtil.getScreenWidth(this) * videoDecoder.getAlignHight() / videoDecoder.getAlignWidth();
                        playbackHeight += DimenUtil.dp2px(this, 50);
                        TGLog.d("CameraPlayerView","curPlayerHeight222 " + playbackHeight);
                        cameraViewLayoutParams.height = playbackHeight;
                    }else{
                        playbackHeight += DimenUtil.dp2px(this, 50);
                    }

                    cameraViewLayoutParams.height = Math.max(cameraViewLayoutParams.height, playbackHeight);
                }

                TGLog.d("CameraPlayerView","h450 = " + h450 + ",  cameraViewLayoutParams.height = " + cameraViewLayoutParams.height + ", difHeight = " + difHeight);
            }
            if (DeviceHelper.isGPSCar(mDevice) && !isLocalConnect()) {
                cameraViewLayoutParams.height = (int) getResources().getDimension(R.dimen.player_height) + DimenUtil.dp2px(this, 50);
            }

            relCameraView.setLayoutParams(cameraViewLayoutParams);
            mPlayerView.setCameraViewSize(cameraViewLayoutParams.height);
            ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_CONSTRAINT, ConstraintLayout.LayoutParams.MATCH_CONSTRAINT);
            layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
            layoutParams.topToBottom = R.id.rel_camera_view_layout;
            layoutParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
            layoutParams.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
            layoutParams.width = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT;
            mFlContainer.setLayoutParams(layoutParams);
            mFlContainer.setVisibility(View.VISIBLE);

            RelativeLayout.LayoutParams mPlayerLayoutParams = (RelativeLayout.LayoutParams) mPlayerView.getLayoutParams();
            mPlayerLayoutParams.bottomMargin = DimenUtil.dp2px(this, 50);
            mPlayerView.setLayoutParams(mPlayerLayoutParams);
            mPlayerView.requestLayout();

            btnSettings.setVisibility(View.VISIBLE);
            ViewGroup.LayoutParams layoutParams2 = relCameraView.getLayoutParams();
            TGLog.d("CameraPlayerView", "height=" + layoutParams2.height + ",w = " + layoutParams2.width);

            if (mDeviceUIHelper.getPlaybackDisplay() != PLAY_MODE_REALTIME) {
                int time = mPlayBackFragment == null ? 0 : mPlayBackFragment.getNowTimeValue();
                String recordDay = mPlayBackFragment == null ? "" : mPlayBackFragment.getRecordDay();
                TGLog.d("TIME_TEST", "recordDay=" + recordDay + ", time == " + DateUtil.formatTimeHHmmss(time));

                if (time <= 0 || StringUtils.isEmpty(recordDay)) {
                    int pType = CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD;
                    if (mDeviceUIHelper.getPlaybackDisplay() == 2) {
                        pType = CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD;
                    }
                    showPlaybackFragment(layoutParams2, mDeviceUIHelper.getPlaybackDisplay(), pType, false);
                }
                mPlayerView.setZoomView(GONE);
                mPlayerView.setFocusingView(GONE, false);

            } else {
                showLiveFragment(layoutParams2, false);
            }
        }

        showFullSrccenPlayBackControl(!isLandscape);
        mPlayerView.onOrientationChanged(orientation, mDeviceUIHelper.getPlaybackDisplay() != PLAY_MODE_REALTIME, mIsPlayBackRunning);
    }

    private int getNoPTZPlayHeight() {
        int h450 = (int) getResources().getDimension(R.dimen.camera_view_player_height_max);
        if (!DeviceFeatureHelper.supportSpeaker(mDeviceFeature)){
            return UIUtil.getScreenHeight(this);
        }

        // start of 小屏兼容
        h450 = resizeIfNeeded(h450);
        return h450;
    }

    private int getPlayHeight() {
        if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)) {
            if (!DeviceFeatureHelper.supportSpeaker(mDeviceFeature)){
                return UIUtil.getScreenHeight(this);
            }
            return UIUtil.getScreenHeight(this) - UIUtil.dip2px(this, 90);
        }

        int add = 0;
        if (isSupportPresetPointNotMultiChannels() || DeviceHelper.isLamp(mDevice)) {
            add = 80;
            if (DeviceHelper.isLamp(mDevice)){
                if (DeviceFeatureHelper.horZOnly(mDeviceFeature)){
                    add = 50;
                }else if (DeviceFeatureHelper.vertOnly(mDeviceFeature)){
                    add = 50;
                }
            }
        }
        int h450 = (int) getResources().getDimension(R.dimen.camera_view_player_height_max) - DimenUtil.dp2px(this, add);
        if (DeviceFeatureHelper.supportPTZ(mDeviceFeature)) {
            TGLog.d("DeviceFeatureHelper.supportPTZ(mDeviceFeature)" + h450);
            h450 = (int) getResources().getDimension(R.dimen.camera_view_player_height) - DimenUtil.dp2px(this, add);
        } else { // 不支持云台，说明底部只有语音区域，不管单画面还是双画面，都要确认底部区域够不够
            if (!DeviceFeatureHelper.supportSpeaker(mDeviceFeature)){
                return UIUtil.getScreenHeight(this);
            }
            if (DeviceHelper.isLamp(mDevice)){
                h450 = (int) getResources().getDimension(R.dimen.camera_view_player_height) - DimenUtil.dp2px(this, add);
            }else{
                // start of 小屏兼容
                h450 = resizeIfNeeded(h450);
                // end of 小屏兼容
            }
        }

        if (!DeviceFeatureHelper.supportSpeaker(mDeviceFeature)){
            h450 += DimenUtil.dp2px(this, 70);
        }

        return h450;
    }

    private int resizeIfNeeded(final int h450) {
        Log.i(TAG+"-Resize", "resizeIfNeeded: origin = " + h450);
        int ret = h450;
        int screenHeight = UIUtil.getScreenHeight(this);
        final int bottomMinHeightDp = 90; // 根据设计图，底部只有一个对讲按钮的时候，整体高度为 40+50+20 （https://codesign.qq.com/s/dqN292dzAmZaBXe/Yyg5ZpEG21j2lKv/inspect）
        final int bottomMinHeight = UIUtil.dip2px(this, bottomMinHeightDp);
        if (screenHeight - h450 < bottomMinHeight) { // 若按照 h450目前的值，底部空间不足（对讲按钮被挤压），那么重新计算 h450 的值
            ret = screenHeight - bottomMinHeight;
            Log.i(TAG+"-Resize", "resizeIfNeeded: resize as " + ret);
        } else {
            Log.i(TAG+"-Resize", "resizeIfNeeded: no need to resize");
        }
        return ret;
    }


    private void adjustFullScreenView(boolean isPlayback) {
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_CONSTRAINT, ConstraintLayout.LayoutParams.MATCH_CONSTRAINT);
        layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        if (mIsPlayBackRunning || isPlayback) {
            layoutParams.width = DimenUtil.dp2px(this, 130);
        } else {
            layoutParams.width = (int) getResources().getDimension(R.dimen.player_height);
        }

        mFlContainer.setLayoutParams(layoutParams);
    }


    @Override
    protected void onRestart() {
        TGLog.d(TAG, "onRestart");
        super.onRestart();
        mPlayerView.mediaSyncStart();
        mPlayerView.screenSaveEnd();
        if (mOrigin == DeviceListActivity.OPEN_DRIVE_LOCAL) {
            CameraHub.getInstance().setEnableLocalApConnect(false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        TGLog.i(TAG, "CameraViewActivity  onPause");
        if (!(mIsPlayBackRunning &&isPlaybackPause&&!isFinishing())){
            mPlayerView.mediaSyncPause();
        }
        if (mPlayBackFragment != null) {
            mPlayBackFragment.setAnimationsStart(false);
        }

        if (mCamera != null) {
            mCamera.unregisterICameraListener(this);
            mCamera.unregisterCameraAVListener(this);
        }
        if (audioRecorder != null) {
            audioRecorder.pauseRecord();
        }

        stopPlayer();
        if (isFinishing()) {
            if (mLiveViewFragment != null) {
                mLiveViewFragment.unregisterICameraListener();
            }

            if (!mIsPlayBackRunning) {
                mPlayerView.screenSaveLocal();
            }
            onActivityDestroy();

            if (isLocalConnect() || DeviceHelper.notPreconnect(mDevice) || DeviceHelper.isLamp(mDevice)) {
                if (mCamera != null) {
                    mCamera.clearListener();
                    mCamera.disconnect();
                }
                if (isLocalConnect()) {
                    WiFiScanManager.scanner().resetDeviceNetWork(this);
                }
            }
        }else if (DeviceHelper.isLamp(mDevice)){
            if (mCamera != null) {
                mCamera.disconnect();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TangeVideoPlayStatistics.SuccessfulVideoLoad.getInstance().cancelReport();
        AppStatusObserver.getInstance().unregisterListener(mAppStatusChangeListener);
    }

    private void stopPlayer() {
        if (mCamera != null && mCamera.isConnected()) {
            mCamera.stopShow();
            if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)) {
                mCamera.stopShowMini();
            }
            mCamera.stopAudio();
            mCamera.stopSpeaking();
        }

        playerViewRecordSave(true);
        removeSleep();
        removeWatch2Report();
        reportPlayerInfo();
    }

    public void reportPlayerInfo(){
        TGLog.d("reportPlayerInfo");
        if (P2PReport.isPlayerStart && P2PReport.data_bytes > 0){
            String mode = mCamera != null? mCamera.mode : "P2P";
            P2PReport.duration = System.currentTimeMillis() / 1000 - P2PReport.startTime;
            P2PReport.reportPlayInfo(mDevice.uuid, mode);
        }
    }

    public void removeSleep() {
        if (sleepRunnable != null) {
            mHandler.removeCallbacks(sleepRunnable);
        }
    }

    public void removeWatch2Report() {
        watchTimeReport(true);
        if (watchTimeRunnable != null) {
            startLiveTime = 0;
            mHandler.removeCallbacks(watchTimeRunnable);
        }

    }

    private void playerViewRecordSave(boolean jump) {
        if (isSaveing && jump) {
            mPlayerView.recordEnd();
            runOnUiThread(() -> mPlayerView.screenSaveEnd());
            isSaveing = false;
        }
    }

    private void onActivityDestroy() {
        if (audioRecorder != null) {
            audioRecorder.release();
        }

        audioRecorder = null;
        try {
            unregisterReceiver(receiver);
        } catch (Throwable z) {}
        mHandler.removeCallbacksAndMessages(null);
        if ((mOrigin == DeviceListActivity.OPEN_DRIVE_LOCAL || mOrigin == DeviceListBaseActivity.PUSH_TARGET_PALYBACK_SDCARD) && DeviceHelper.isCar(mDevice)) {
            String wifi = ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine() + mDevice.uuid;
            TGLog.d("wifi = " + wifi);
            BizWiFiUtil.removeDeviceWifi();
            WiFiScanManager.scanner().removeNetwork(this, wifi);
            if (mCamera != null) {
                mCamera.disconnect();
                if (mDevice != null) {
                    mCamera.disableLanSearch(mDevice.password);
                }
            }
        }
    }


    public void connect() {
        TGLog.i(TAG, "[connect]");
        if (!isCanDo() && !isLocalConnect()) return;
        if (isLocalConnect()) {
            if (!WiFiUtilWrapper.checkWifiAndLocation(this)) return;
        }
        if (!reConnected) {
            TGLog.d("========TEST====", "2");
            autoCameraLoading();
        } else if (mCamera != null) {
            String log = String.format("P2P_LIVE_CONNECT_START  p2p:%s uuid:%s recTime:%s", mCamera.p2pid, mCamera.uid, DateUtil.getCurrentTime());
            TGLog.i(TAG, log);
            LogUtils.uploadLogN("P2p_live", log);
        }
        TGLog.i(TAG, "reConnected=" + reConnected);
        if (mCamera != null) {
            reportFirstFramePrepare();
            setCameraListener();
            mCamera.connect();
        }
    }

    public void reportFirstFramePrepare() {
        if (!connectCallBefore) {
            TangeVideoPlayStatistics.SuccessfulVideoLoad.getInstance().reportFailedInTheFuture();
            TangeVideoPlayStatistics.reportRealTimeFirstFramePrepare(DeviceTypeHelper.isWifiDevice(mDevice.device_type));
            TangeVideoPlayStatistics.resetStartTimeP2P();
            connectCallBefore = true;
        }
    }

    private boolean isCanDo() {
        if (mIsUserOffline) {
            TGLog.d("isUserOffline");
            return false;
        }
        if (DeviceHelper.isDeviceForeignIccid(mDevice)) {
            TGLog.d("isUserOffline1");
            setDeviceForeignIccId();
            return false;
        }
        if (DeviceHelper.is4GExpired(mDevice) && !DeviceHelper.isCar(mDevice)) {
            setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_DEVICE_SERVICE_EXPIRED, true);
            TGLog.d("isUserOffline2");
            return false;
        }


        if (DeviceHelper.isCarPrimary(mDevice) && mOrigin != DeviceListBaseActivity.OPEN_DRIVE_LOCAL && !mIsPlayBackRunning) {
            if (DeviceHelper.isCarPrimary(mDevice)) {
                if (watchTime == null && DeviceHelper.isOnline(mDevice)) return false;
                if (CarWatchTimeHelper.isCarPrimaryWatchExpired(watchTime)) {
                    setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_CAR_PRIMARY, true);
                    return mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_BACK_SDCARD;
                }
                if (CarWatchTimeHelper.isCarPrimaryWatchEnd(watchTime)) {
                    setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_CAR_PRIMARY_WATCH_END, true);
                    mPlayerView.setWatchTime(null);
                    return false;
                }
                TGLog.d("isUserOffline5");

            } else if (DeviceHelper.isCarExpired(mDevice) || DeviceHelper.is4GExpired(mDevice)) {
                setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_DEVICE_SERVICE_EXPIRED, false);
                TGLog.d("isUserOffline3");
                return false;
            }
        }

        if (!DeviceHelper.isOnline(mDevice) && !isLocalConnect() && playType != CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD) {//eviceHelper.is4GDevice(mDevice) &&
            setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_DEVICE_OFFLINE, false);
            TGLog.d("isUserOffline4");
            return false;
        }
        if (mIsPlayBackRunning && playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD && mPlayBackFragment != null) {
            if (mPlayBackFragment.getSdCardSize() == 0) {
                setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_SDCARD_NONE, false);
                TGLog.d("isUserOffline6");
                return false;
            }
            if (mPlayBackFragment.getSdCardSize() == -1) {
                setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_SDCARD_EXCEPTION, false);
                TGLog.d("isUserOffline7");
                return false;
            }
        }
        return true;
    }

    private void setPlayerStatus(int status, boolean setClick) {
        runOnUiThread(() -> {
            mPlayerView.setPlayerStatus(status);
            if (setClick) {
                setLiveClicked(false);
            }
        });
    }

    public void setLiveClicked(boolean b) {
        if (mLiveViewFragment != null) {
            mLiveViewFragment.setClicked(b);
        }
    }

    public boolean autoCameraLoading() {
        if (DeviceHelper.isOff(mDevice)) {
            TGLog.d("DeviceSettingsActivity", "STATUS_ERROR_DEVICE_OFF = ");
            setDeviceClose();
            return false;
        }
        if (DeviceHelper.isDeviceForeignIccid(mDevice)) {
            setDeviceForeignIccId();
            return false;
        } else if (!DeviceHelper.isOnline(mDevice) && !isLocalConnect()) {
            mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_DEVICE_OFFLINE);
            return false;
        }
        if (!isLocalConnect() && !mIsPlayBackRunning) {
            if (DeviceHelper.isCarPrimary(mDevice)) {
                if (watchTime == null) return false;
                if (CarWatchTimeHelper.isCarPrimaryWatchExpired(watchTime)) {
                    mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_CAR_PRIMARY);
                    return false;
                }
                if (CarWatchTimeHelper.isCarPrimaryWatchEnd(watchTime)) {
                    mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_CAR_PRIMARY_WATCH_END);
                    return false;
                }
            } else if (DeviceHelper.isCarExpired(mDevice) || DeviceHelper.is4GExpired(mDevice)) {
                mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_DEVICE_SERVICE_EXPIRED);
                return false;
            }
        }

        ActivityHelper.showLoading(this, mPlayerView);
        return true;
    }

    public void startPlayback() {
        if (mPlayBackFragment != null && mPlayBackFragment instanceof SdCardPlayBackFragment) {
            mPlayBackFragment.rePlayCurrentTime();
        }
    }

    private void getPresetPointsEnableCMD(){
        Object object = TGApplicationBase.getInstance().getGlobalObject(mDevice.uuid + PRE_POSITION);
        if (object == null){
            if (mCamera != null && mCamera.isConnected()){
                TGApplicationBase.getInstance().putGlobalObject(mDevice.uuid + PRE_POSITION, true);
                CameraHelper.getPresetPointsEnableCMD(mCamera);
            }
        }
    }

    public void startLive() {
        getPresetPointsEnableCMD();
        setLiveClicked(true);
        startLiveMini();
        if (!isMuteOn) {
            if (mCamera != null) {
                mCamera.startAudio();
            }
        }
        boolean supportTalkBack = CameraViewHelper.isTalkback2W(getBaseContext());
        if (supportTalkBack){
            startAudioRecoder();
        }
        int stream = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
        if (!(DeviceHelper.isCar(mDevice) && mOrigin == DeviceListActivity.PUSH_TARGET_LIVE) || DeviceHelper.isBatteryDevice(mDevice) || CameraHub.getInstance().isEnableLocalApConnect()) {
            if (deviceSettingsInfo != null) {
                stream = deviceSettingsInfo.quality;
                if (stream == 0) {
                    stream = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
                    if (DeviceHelper.isCar(mDevice) || DeviceHelper.isBatteryDevice(mDevice)){
                        stream = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MAX;
                    }
                }
            }
        }

        if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)) {
            int quality = deviceSettingsInfo != null? deviceSettingsInfo.quality : 0;
            if (quality == 0){
                TGThreadPool.executeDelay(() -> setMultiChannelsStreamCtrl(channel), 1000);
            }else{
                setMultiChannelsStreamCtrl(channel);
            }
        } else {
            setStreamCtrlCMD(stream, 0);
        }

        mHandler.removeMessages(EVENT_BITRATE);
        mHandler.sendEmptyMessageDelayed(EVENT_BITRATE, 1000);
        getDeviceStatusInfo();
        requestDeviceSleep();
    }

    public void reportFirstFrameP2P() {
        if (!startShowCallBefore) {
            TangeVideoPlayStatistics.reportRealTimeFirstFrameP2P(DeviceTypeHelper.isWifiDevice(mDevice.device_type));
            TangeVideoPlayStatistics.resetStartTimeRequestVideoData();
            startShowCallBefore = true;
        }
    }



    public void requestDeviceSleep() {
        if (isLocalConnect()) return;
        if (DeviceHelper.mustSleep(mDevice) && isCanDo()) {
            if (sleepRunnable == null) {
                sleepRunnable = () -> {
                    mPlayerView.mediaSyncPause();
                    startActivityForResult(new Intent(getBaseContext(), SleepLockActivity.class), 0);
                    mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_DEVICE_SLEEP);
                };
            }
            long sleep = CommonConstants.SLEEP_LOCK_TIME_DEFAULT;
            if (deviceSettingsInfo.sleepTime != 0) {
                sleep = deviceSettingsInfo.sleepTime;
            }
            TGLog.i(TAG, "deviceSettingsInfo sleepTime: " + sleep / 1000);
            mHandler.removeCallbacks(sleepRunnable);
            mHandler.postDelayed(sleepRunnable, sleep);
        }
    }

    private Runnable watchTimeRunnable;

    public void requestWatchTime() {
        if (isLocalConnect()) return;

        if (DeviceHelper.isCarPrimary(mDevice) && !CarWatchTimeHelper.isCarPrimaryWatchEnd(watchTime)) {
            final long sec = 60 * 1000;
            startLiveTime = System.currentTimeMillis();
            if (watchTimeRunnable == null) {
                watchTimeRunnable = () -> {
                    long delay = sec;
                    if (watchTime != null) {
                        watchTimeReport(false);
                        watchTime.setUsed(watchTime.getUsed() + 60);
                        if (watchTime.getAvailable() < 60) {
                            delay = watchTime.getAvailable() * 1000L;
                        }
                        if (!watchTime.isAvailable()) {
                            mPlayerView.setWatchTime(null);
                            TGLog.i(TAG, "requestWatchTime stopPlayer ：" + delay);
                            stopPlayer();
                            cameraDisconnect();
                            return;
                        }
                    }
                    TGLog.i(TAG, "requestWatchTime delay ：" + delay);
                    mHandler.postDelayed(watchTimeRunnable, delay);
                };
            }

            mHandler.removeCallbacks(watchTimeRunnable);
            mHandler.postDelayed(watchTimeRunnable, sec);
        }
    }

    public WatchTime getWatchTime() {
        return watchTime;
    }

    private void startLiveMini() {
        if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature) && mCamera != null) {
            mCamera.startShowMini();
        }
    }

    private void setStreamCtrlCMD(int type, int channel) {
        if (!(DeviceHelper.isCar(mDevice) && mOrigin == DeviceListActivity.PUSH_TARGET_LIVE) || DeviceHelper.isBatteryDevice(mDevice) || CameraHub.getInstance().isEnableLocalApConnect()) {
            if (deviceSettingsInfo != null && mDeviceFeature != null) {
                if (channel == 0){
                    deviceSettingsInfo.quality = type;
                }else{
                    deviceSettingsInfo.quality2 = type;
                }

            }
        }
        cmdHelper.setStreamCtrlCMD(channel, type);
        TGLog.i(TAG, "setStreamCtrlCMD type = " + type);
        TGLog.i(TAG, "setStreamCtrlCMD channel = " + channel);
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        TGLog.i(TAG, "onConfigurationChanged");
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            TGApplicationBase.getInstance().removeGlobalObject(BottomSheetListDialog.ACTION_RESOLUTION);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            setupSurfaceView(newConfig.orientation);
        }
    }

    @Override
    public void receiveVideoData(final AVFrames avFrame) {
        TGLog.d("TGLoading", "mIsPlayblackRunning " + mIsPlayBackRunning + ", playType = " + playType);
        reportFirstFrameDecode();

        if (!P2PReport.isPlayerStart){
            P2PReport.initPlayerInfo();
            P2PReport.isPlayerStart = true;
            if (playType == CommonConstants.CAMERA_TYPE_LIVE || !mIsPlayBackRunning){
                P2PReport.playType = CommonConstants.CAMERA_TYPE_LIVE;
            }else{
                P2PReport.playType = playType;
            }
        }
        if (avFrame != null && mCamera != null && mCamera.getClickTime() > 0 && (playType == CommonConstants.CAMERA_TYPE_LIVE || playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD)) {
            P2PReport.reportFirstAVFrame(mCamera, deviceSettingsInfo, mDevice, String.valueOf(playType), getFrom());
            mCamera.setClickTime(0);
        }
        mPlayerView.receiveVideoData(avFrame);
        assert avFrame != null;
        byte[] data = avFrame.getData();
        saveToLocalIfNeeded(data);

        if (mDeviceFeature != null && mDeviceFeature.recordFun != 0){
            TGThreadPool.executeOnUiThread(() -> {
                if (mDeviceFeature.recordFun != avFrame.getRecordEnable()){
                    mDeviceFeature.recordFun = avFrame.getRecordEnable();
                    if (mPlayerView != null){
                        mPlayerView.initDeviceInfo();
                    }
                }
                TGLog.d("CameraViewActivity", "mDeviceFeature.recordFun receiveVideoData = " + mDeviceFeature.recordFun);
            });
        }

        if (data != null && data.length > 0) {
            videoSize += data.length;
            P2PReport.data_bytes += data.length;
        }
        getGetEnv();
    }

    /**
     * 保存视频帧数据到本地，用于问题定位，仅在开关打开时执行此方法。
     *
     */
    private void saveToLocalIfNeeded(byte[] data) {
        if (DevToolsActivity.enableWriteVideoDataToLocalFile) {
            if (localVideoDataUtil == null) {
                localVideoDataUtil = new LocalVideoDataUtil(deviceSettingsInfo, mCamera);
            }
            localVideoDataUtil.append(data);
        }
    }


    private VideoDecoder getMediaSync(){
        if (mPlayerView.getPlayerView() instanceof CameraPlayerPiPView) {
            return  ((CameraPlayerPiPView) mPlayerView.getPlayerView()).getMediaSyncMini();
        }
        return mPlayerView.getMediaSync();
    }

    private OnMediaFormatChangedListener mOnMediaFormatChangedListener = () -> {
        VideoDecoder sync2 = getMediaSync();
        if (sync2 != null){
            TGLog.d("CameraPlayerView", "setLivePortraitLayout89 width =  "+ sync2.getAlignWidth() + ", height = " + sync2.getAlignHight());
            mPlayerView.updateCameraViewSize();
        }

        if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
            if (!recviceVideoDataCardCallBefore) {
                TangeVideoPlayStatistics.reportPlaybackFirstFrameDecode(DeviceTypeHelper.isWifiDevice(mDevice.device_type), false);
                TangeVideoPlayStatistics.reportPlaybackFirstFrameTotal(DeviceTypeHelper.isWifiDevice(mDevice.device_type), false);
                recviceVideoDataCardCallBefore = true;
            }
        }else if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD) {
            if (!recviceVideoDataCloudCallBefore) {
                TangeVideoPlayStatistics.reportPlaybackFirstFrameDecode(DeviceTypeHelper.isWifiDevice(mDevice.device_type), true);
                TangeVideoPlayStatistics.reportPlaybackFirstFrameTotal(DeviceTypeHelper.isWifiDevice(mDevice.device_type), true);
                recviceVideoDataCloudCallBefore = true;
            }
        }else{
            if (!recviceVideoFormatCallBefore) {
                TangeVideoPlayStatistics.reportRealTimeFirstFrameDecode(DeviceTypeHelper.isWifiDevice(mDevice.device_type));
                TangeVideoPlayStatistics.reportRealTimeFirstFrameTotal(DeviceTypeHelper.isWifiDevice(mDevice.device_type));
                TangeVideoPlayStatistics.SuccessfulVideoLoad.getInstance().reportSuccessIfNeeded();
                recviceVideoFormatCallBefore = true;
            }

            if (!recviceVideoDataCallBefore) {
                TangeVideoPlayStatistics.reportRealTimeFirstFrameData(DeviceTypeHelper.isWifiDevice(mDevice.device_type));
                TangeVideoPlayStatistics.resetStartTimeDecode();
                recviceVideoDataCallBefore = true;
            }
        }
    };


    private void reportFirstFrameDecode() {
        try {
            if (mPlayerView != null){
                mPlayerView.setFormatChangedListener(mOnMediaFormatChangedListener);
            }
            reportCardFirstFrameDecode();
            reportRealTimeFirstFrameDecode();
        } catch (Throwable ex) {
            TGLog.i(TAG, "reportFirstFrameDecode: error = " + ex);
        }
    }

    private void reportCardFirstFrameDecode() {

        if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {

            if (mPlayBackFragment == null || !mPlayBackFragment.isVisible() || mPlayBackFragment.getTGPlayback() == null || !mPlayBackFragment.getTGPlayback().isPlaybackRecordCalledBefore()) {
                TGLog.i(TAG, "reportCardFirstFrameDecode: skip reportCardFirstFrameDecode, because not called play a time before !");
                return;
            }

            if (!recviceVideoDataCardOutsideCallBefore) {
                TangeVideoPlayStatistics.reportPlaybackFirstFrameDownload(DeviceTypeHelper.isWifiDevice(mDevice.device_type), false);
                TangeVideoPlayStatistics.resetStartTimePlayBackDecode();
                recviceVideoDataCardOutsideCallBefore = true;
            }
        }
    }
    @Override
    public void onAdjustHeight(){
        if (isLandscape){
            return;
        }
        if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD || playType == CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD) {
            int playbackHeight = CameraViewHelper.getPlaybackHeight(mDeviceFeature, this);
            int curPlayerHeight = mPlayerView.getCurPlayerHeight() + DimenUtil.dp2px(this, 50);
            TGLog.d("CameraPlayerView", "setLivePortraitLayout999 playbackHeight = " + playbackHeight + ", h = " + curPlayerHeight);
            playbackHeight = Math.max(playbackHeight, curPlayerHeight);
            if (mPlayerView.getCurPlayerHeight() != 0){
                playbackHeight = curPlayerHeight;
            }

            ConstraintLayout.LayoutParams cameraViewLayoutParams = (ConstraintLayout.LayoutParams) relCameraView.getLayoutParams();
            TGLog.d("CameraPlayerView", "setLivePortraitLayout99 playbackHeight =  "+ playbackHeight+ ", height = " + cameraViewLayoutParams.height);
            if (playbackHeight != cameraViewLayoutParams.height){
                cameraViewLayoutParams.width = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT;
                cameraViewLayoutParams.height = playbackHeight;
                mPlayerView.setCameraViewSize(playbackHeight);
                relCameraView.setLayoutParams(cameraViewLayoutParams);

                relCameraView.requestLayout();
            }
        }

    }

    private void reportRealTimeFirstFrameDecode() {
        if (playType == CommonConstants.CAMERA_TYPE_LIVE) {
            if (!recviceVideoDataCallBefore) {
                TangeVideoPlayStatistics.reportRealTimeFirstFrameData(DeviceTypeHelper.isWifiDevice(mDevice.device_type));
                TangeVideoPlayStatistics.resetStartTimeDecode();
                recviceVideoDataCallBefore = true;
            }
        }
    }

    @Override
    public void receiveSubVideoData(AVFrames avFrame) {
        reportFirstFrameDecode();
        runOnUiThread(() -> mPlayerView.receiveVideoMiniData(avFrame));
    }


    public void getGetEnv() {
        if (!isGetEnv && mCamera != null && mCamera.isConnected()) {
        //    DeviceInteraction.create(device).getFeatureList();
            mCamera.sendIOCtrl(AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETRECORD_REQ, AVIOCTRLDEFs.SMsgAVIoctrlGetRecordReq.parseContent(0));

            CameraHelper.getDeviceRunTimeState(mCamera);
            isGetEnv = true;
        }
    }

    private void setSpeed(int speed) {
        mPlayerView.setSpeed(speed);
        if (mCamera != null && mCamera.isConnected() || mPlayerView.getCameraType() == CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD) {
            TGLog.d("EVENT_PLAY_TOOBAR_HIDE6");
            mHandler.sendEmptyMessageDelayed(EVENT_PLAY_TOOBAR_HIDE, HIDE_TIME);
        }
        if (isPlaybackFragmentVisible()) {
            mPlayBackFragment.setSpeed(speed);
        }
    }

    boolean isPlaybackFragmentVisible() {
        return mPlayBackFragment != null && mPlayBackFragment.isVisible();
    }

    @Override
    public void receiveAudioData(final AVFrames avFrame) {
        mPlayerView.receiveAudioData(avFrame);
        if (avFrame != null){
            byte[] data = avFrame.getData();
            if (data != null && data.length > 0){
                P2PReport.data_bytes += data.length;
            }
        }
    }

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    public void onBackPressed() {
        if (isLandscape) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            onScreenClick();
        } else {
            finish();
        }
    }

    @Override
    public void receiveUpdateConnectStates(final int state) {
        TGLog.d(TGLog.TAG, "state = " + state);

        runOnUiThread(() -> {
            if (state == Camera.CONNECTION_STATE_CONNECTED) {
                mPlayerView.mediaSyncStart();
                reConnected = false;
                getPresetPointsEnableCMD();
                if (isLiveFragmentVisiable() || mPlayBackFragment != null && !mIsPlayBackRunning) {
                    startLive();
                    if (mPlayBackFragment != null) {
                        mPlayBackFragment.rePlayCurrentTime();
                    }

                } else if (mPlayBackFragment != null) {
                    getGetEnv();
                    mPlayBackFragment.rePlayCurrentTime();
                }
                setLiveClicked(true);
                mPlayerView.initDeviceInfo();
            } else if (state == Camera.SESSION_TIME_OUT){
                if (playType == CommonConstants.CAMERA_TYPE_LIVE || !mIsPlayBackRunning) {
                    mHandler.removeMessages(EVENT_SESSION_TIME_OUT);
                    mHandler.sendEmptyMessageDelayed(EVENT_SESSION_TIME_OUT, 1000);
                }

            } else if (state == CONNECTION_STATE_SESSION_CLOSED_TIMEOUT) {
                removeWatch2Report();
                mHandler.removeMessages(EVENT_PLAY_RECONNECTED);
                mHandler.sendEmptyMessageDelayed(EVENT_PLAY_RECONNECTED, (reConnectedCount + 1) * 1000);
            } else if (state == Camera.CONNECTION_STATE_WRONG_PASSWORD) {
                getPassword();
            }else if (state == Camera.CONNECTION_STATE_CONNECTING){
                autoCameraLoading();
            } else if (state!=Camera.SESSION_TIME_OUT_FIXED) {
                removeWatch2Report();
                cameraDisconnect();
                if (playType != CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD || !mIsPlayBackRunning) {
                    if (isLocalConnect()) {
                        WifiAp wifiAp = NetworkUtil.getConnectWifiSSID(getBaseContext());
                        if (!TextUtils.isEmpty(wifiAp.ssid) && wifiAp.ssid.startsWith(ApScanConfiguration.INSTANCE.apNamePrefix())) {
                            SystemClock.sleep(1000);
                            connect();
                        } else {
                            mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_CAR_LOCAL_NETWORK_ERROR);
                        }
                    }else if (state == Camera.CONNECTION_STATE_DISCONNECTED){
                       if (mPlayBackFragment instanceof SdCardPlayBackFragment){
                           if (mPlayBackFragment.getSdCardSize() == 0) {
                               mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_SDCARD_NONE);
                               return;
                           }
                       }
                       mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_NETWORK_ERROR);
                    }else if (state == Camera.CONNECTION_STATE_CONNECT_FAILED){
                        Device device = DeviceItem.createBasicDevice(mDevice);
                        if (CameraHub.getInstance().supportDowngrade(device)){
                            mCamera = CameraHub.getInstance().downgrade(device);
                            mCamera.registerICameraListener(this);
                            if (mLiveViewFragment!=null){
                                mLiveViewFragment.onResume();
                            }else if (mPlayBackFragment!=null){
                                mPlayBackFragment.onResume();
                            }

                        }
                    }
                }
            }

            if (state != Camera.CONNECTION_STATE_CONNECTED) {
                hidePlayerInfoView();
            }
        });
    }

    private boolean isLiveFragmentVisiable() {
        return mLiveViewFragment != null && mLiveViewFragment.isVisible();
    }

    private void watchTimeReport(boolean isStop) {
        if (isLocalConnect()) return;
        TGLog.trace(" watchTimeReport " + startLiveTime + " " + JSON.toJSONString(isStop));
        if (watchTime != null && DeviceHelper.isCarPrimary(mDevice) && !CarWatchTimeHelper.isCarPrimaryWatchEnd(watchTime) && startLiveTime > 0) {
            long end = System.currentTimeMillis() / 1000;
            long start = startLiveTime / 1000;
            HashMap<String, String> map = new HashMap<>();
            TGLog.i(TAG, "requestWatchTime: " + (end - start));
            map.put("uuid", mDevice.uuid);
            map.put("start_time", String.valueOf(start));
            map.put("end_time", String.valueOf(end));
            TGHttp.getInstance().watchTimeReport(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ClientObserver<String>() {
                        @Override
                        protected void onSuccess(String content) {
                            if (!isStop) {
                                startLiveTime = System.currentTimeMillis();
                                return;
                            }
                            if (isLocalConnect()) return;
                            CarWatchTimeHelper.watchTimeQuery(mDevice.uuid, time -> watchTime = time);
                        }
                    });
        }
    }

    void cameraDisconnect() {
        setLiveClicked(false);
        if (playType != CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD || !mIsPlayBackRunning) {
            setToolbarVisibility(View.VISIBLE);
            mPlayerView.setToolbarVisibility(View.GONE);
            if (!isLocalConnect()) {
                if (!DeviceHelper.isOnline(mDevice)) {
                    mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_DEVICE_OFFLINE);
                } else if (deviceSettingsInfo.deviceStatus != DeviceStateConstants.DEVICE_OPEN) {
                    setDeviceClose();
                } else if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD && mIsPlayBackRunning) {
                    if (mPlayBackFragment != null && mPlayBackFragment.getSdCardSize() == 0) {
                        mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_SDCARD_NONE);
                    } else if (mPlayBackFragment != null && mPlayBackFragment.getSdCardSize() == -1) {
                        mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_SDCARD_EXCEPTION);
                    }
                } else {
                    mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_NETWORK_ERROR);
                }
            }
        }
    }


    private void showCameraViewContainer(boolean show){
        if (mLiveViewFragment != null && mPlayBackFragment == null){
          //  findViewById(R.id.camera_view_container).setVisibility(show? VISIBLE : GONE);
        }else{
        //    findViewById(R.id.camera_view_container).setVisibility(VISIBLE);
        }

    }

    @Override
    public void receiveIOCtrlData(final int type, final byte[] data) {
        boolean isDriveRec = mDeviceFeature != null && mDeviceFeature.isDriveRec;
        super.receiveIOCtrlData(type, data);
        runOnUiThread(() -> {
            if (type == AVIOCTRLDEFs.TCI_CMD_GET_RUNTIME_STATE_RESP){
                if (mDeviceFeature != null){
                    mDeviceFeature.recordFun = 1;
                    putSettingsInfo();
                }
                mPlayerView.initDeviceInfo();

            }else if (type == AVIOCTRLDEFs.TCI_CMD_GET_MICROPHONE_RESP) {
                byte b = Packet.byteArrayToByte_Little(data, 4);
                deviceSettingsInfo.microphoneOn = b;
                TGLog.d("CameraViewActivity",  "info.b = " + b);
                isMicrophoneClose();
                putSettingsInfo();
            } else if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP) {
                mPlayerView.setDeviceFeature(mDeviceFeature);
                mPlayerView.initZoomLenses();
                mPlayerView.initFocusView();
                if (!isDriveRec && mDeviceFeature != null && mDeviceFeature.isDriveRec) {
                    mPlayerView.playerHide();
                }
                if (DeviceHelper.isLamp(mDevice) && mCamera != null){
                    CameraHelper.getLightState(mCamera);
                }

                if (DeviceFeatureHelper.isSupportMicrophoneSetting(mDeviceFeature) && !mDevice.isShare()){
                    if (mCamera != null){
                        mCamera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_GET_MICROPHONE_REQ, new byte[1]);
                    }
                }
                if (playType == CommonConstants.CAMERA_TYPE_LIVE) {
                    //isMicrophoneClose();
                    if (DeviceFeatureHelper.supportPTZ(mDeviceFeature) && mLiveViewFragment != null && mLiveViewFragment.getPtzControlViewVisible() == View.GONE) {
                        setHeight();
                        ViewGroup.LayoutParams layoutParams = relCameraView.getLayoutParams();
                        createValueAnimate(layoutParams.height, playHeight, 100, "serve");

                    } else if (mLiveViewFragment != null){
                        mLiveViewFragment.updateDeviceFeature(mDeviceFeature);
                    }
                    startLiveMini();
                    if (DeviceHelper.isBatteryDevice(mDevice) || DeviceHelper.isSolar(mDevice)){
                        getDeviceStatusInfo();
                    }
                    if (mDeviceFeature != null) {
                        if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)) {
                            if (mCamera != null) {
                                mCamera.getPrimaryViewCmd();
                                if (!StringUtils.isEmpty(mDeviceFeature.zoomMode) && mDeviceFeature.zoomMode.contains("times:")){
                                    mCamera.getZoomOr2LensesCMD(0);
                                }
                                if (!StringUtils.isEmpty(mDeviceFeature.zoomMode2) && mDeviceFeature.zoomMode2.contains("times:")){
                                    mCamera.getZoomOr2LensesCMD(1);
                                }
                            }

                        } else {
                            if (mDeviceFeature.support2Lenses || mDeviceFeature.supportZoom) {
                                if (mDeviceFeature.is2LensesCapZoom()) {
                                    if (mCamera != null) {
                                        mCamera.get2LensesCapZoomCMD();
                                    }
                                }
                                if (mCamera != null) {
                                    mCamera.getZoomOr2LensesCMD();
                                }
                            }
                        }
                    }
                    setHeight();
                    ViewGroup.LayoutParams layoutParams = relCameraView.getLayoutParams();
                    if (layoutParams.height != playHeight) {
                        createValueAnimate(layoutParams.height, playHeight, 100, "serve");
                    }
                } else {
                    if (DeviceFeatureHelper.supportPTZ(mDeviceFeature)) {
                        setHeight();
                    }
                }
                mPlayerView.setResolution(mPlayerView.getCurrentPlayer() == 0? deviceSettingsInfo.quality : deviceSettingsInfo.quality2);

                if (deviceSettingsInfo.deviceStatus != DeviceStateConstants.DEVICE_OPEN && !mIsPlayBackRunning) {
                    setDeviceClose();
                }
                if (mPlayBackFragment != null) {
                    mPlayBackFragment.setSdCardSize(deviceSettingsInfo.total, true);
                }

                if (!DeviceFeatureHelper.supportSpeaker(mDeviceFeature) && !DeviceFeatureHelper.supportPTZ(mDeviceFeature)){
                    setHeight();
                }
            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSTREAMCTRL_RESP) {
                deviceSettingsInfo.quality = data[4];
            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETRECORD_RESP) {
                deviceSettingsInfo.recordType = Packet.byteArrayToInt_Little(data, 4);
                if (data.length > 8) {
                    deviceSettingsInfo.recordStream = data[8];
                }
                TGLog.d("VideoType", "recordType2 = " + deviceSettingsInfo.recordType);
                putSettingsInfo();
                mPlayerView.initDeviceInfo();
            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_RESP) {
                if ((!(DeviceHelper.isCar(mDevice) && mOrigin == DeviceListActivity.PUSH_TARGET_LIVE) || DeviceHelper.isBatteryDevice(mDevice))) {
                    putSettingsInfo();
                }
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PTZ_POS_RESP) {
                int zPos = Packet.byteArrayToInt_Little(data, 8);
                int channel = 0;
                if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature) && data.length >= 16){
                    channel = Packet.byteArrayToInt_Little(data, 12);
                }
                float zoomPos = Float.intBitsToFloat(zPos);
                if (zoomPos<0||zoomPos>1){
                    zoomPos =0;
                }
                zoomPos = DeviceFeatureHelper.analogZoom(mDeviceFeature, zoomPos, channel);
                if (!DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)){
                    updateLensesCapZoom(zoomPos);
                }
                TGLog.d(ZoomView.TAG, "deviceSettingsInfo.zoomPos: "+deviceSettingsInfo.zoomPos+" zPos = "  + zPos + "zoomPos = " + zoomPos + ", channel = " + channel + ", data.length = " + data.length);
                updateZoomLensesUISave(zoomPos, channel);
                if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)){
                    DeviceFeature.ZoomFeature zoomFeature = mDeviceFeature.getZoomFeature(channel);
                    if (zoomFeature != null){
                        TGLog.d(ZoomView.TAG, "1111startAnalogZoom = " + zoomFeature.startAnalogZoom);
                        if (zoomFeature.startAnalogZoom){
                            analogZoom(zoomPos, 0, false, channel, ZOOM_INIT);
                        }
                    }else {
                        TGLog.d(ZoomView.TAG, "zoomFeature == null, channel = " + channel);
                    }


                }
                if (mLiveViewFragment instanceof CameraLiveFragment) {
                    ((CameraLiveFragment) mLiveViewFragment).setPtzPos(CameraHelper.getPtzPosResp(data));
                }
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PRIMARY_VIEW_RESP) {
                int pos = Packet.byteArrayToInt_Little(data, 4);
                mDeviceFeature.currentPlayer = pos;
                deviceSettingsInfo.zoomPos = pos;
                mPlayerView.switchPlayer(pos, isLocalStreamMax());
                putSettingsInfo();
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_LIGHT_RESP){
                CameraHelper.getLightData(data, mDeviceFeature);
                putSettingsInfo();
                if (mLiveViewFragment != null) {
                    mLiveViewFragment.updateDeviceFeature(mDeviceFeature);
                }
            }  else if (type == AVIOCTRLDEFs.TCI_CMD_GET_WATCHPOS_RESP || type == AVIOCTRLDEFs.TCI_CMD_GET_ALARMTONE_CAP_RESP || type == AVIOCTRLDEFs.TCI_CMD_GET_HINTTONE_RESP) {
                if (mLiveViewFragment instanceof CameraLiveFragment) {
                    ((CameraLiveFragment) mLiveViewFragment).receiveIOCtrlData(type, data);
                }
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PTZ_TRACK_RESP){
                boolean isCruiseEnable = CameraHelper.isCruiseEnable(data);
                TGLog.d("isSupportPresetPoint = " + isCruiseEnable);
                if (isCruiseEnable){
                    deviceSettingsInfo.maxTracks = CameraHelper.getCruiseMaxPspResp(data);
                    deviceSettingsInfo.tracksType = CameraHelper.getCruiseTrackType(data);
                    TGLog.d("maxTracks = " + deviceSettingsInfo.maxTracks);
                    TGLog.d("tracksType = " + deviceSettingsInfo.tracksType);
                    putSettingsInfo();

                    return;
                }

                if (mLiveViewFragment instanceof CameraLiveFragment) {
                    ((CameraLiveFragment) mLiveViewFragment).receiveIOCtrlData(type, data);
                }

            }
            else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PSP_RESP) {
                boolean isSupportPresetPoint = CameraHelper.isPresetPointsEnable(data);
                TGLog.d("isSupportPresetPoint = " + isSupportPresetPoint);
                if (isSupportPresetPoint){
                    deviceSettingsInfo.maxPresetPoint = CameraHelper.getPresetPointsMaxPspResp(data);
                    deviceSettingsInfo.isSupportPresetPoint = true;
                    TGLog.d("maxPresetPoint = " + deviceSettingsInfo.maxPresetPoint);
                    putSettingsInfo();
                    return;
                }

                short posType = CameraHelper.getPresetPointsTypeResp(data);
                if (mLiveViewFragment instanceof CameraLiveFragment) {
                    ((CameraLiveFragment) mLiveViewFragment).receiveIOCtrlData(type, data);
                }
                if (posType == AVIOCTRLDEFs.PSP_BY_POS) {
                    //AVIOCTRLDEFs.PSP_F_ZOOMONLY
                    List<DevicePresetPoints> devicePresetPoints = CameraHelper.getPresetPointsResp(data,true);
                    for (DevicePresetPoints p : devicePresetPoints) {
                        if (p.flags == AVIOCTRLDEFs.PSP_F_ZOOMONLY && mDeviceFeature != null && mDeviceFeature.is2LensesCapZoom()) {
                            updateLensesCapZoom(p.pos.z);
                        }
                    }
                }

            } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
                int command = Packet.byteArrayToInt_Little(data, 0);
                int result = Packet.byteArrayToInt_Little(data, 4);
                if (mLiveViewFragment instanceof CameraLiveFragment) {
                    ((CameraLiveFragment) mLiveViewFragment).receiveIOCtrlData(type, data);
                }
                TGLog.d(ZoomView.TAG, "command" + command + ",result:" + result);
                if (command == AVIOCTRLDEFs.TCI_CMD_GET_RUNTIME_STATE_REQ){
                    if (result == 3 || result == 4){
                        if (mDeviceFeature != null){
                            mDeviceFeature.recordFun = 0;
                            putSettingsInfo();
                        }
                        mPlayerView.initDeviceInfo();
                    }
                } else if (command == AVIOCTRLDEFs.TCI_CMD_GET_WIFI_SIGNALLEVEL_REQ){
                    TGLog.d("len = " + data.length);
                } else if (command == AVIOCTRLDEFs.TCL_CMD_SET_CAMERA_STATUS_REQ) {
                    TGLog.d("DeviceSettingsActivity", "mDeviceUIHelper.isClickOpenDeviceBtn():" + mDeviceUIHelper.isClickOpenDeviceBtn());
                    if (result == 0 && mDeviceUIHelper.isClickOpenDeviceBtn()) {
                        mDevice.is_open = DeviceStateConstants.DEVICE_OPEN;
                        deviceSettingsInfo.deviceStatus = DeviceStateConstants.DEVICE_OPEN;
                        mPlayerView.setBackgroud();
                        if (mPlayBackFragment != null) {
                            mPlayBackFragment.setDeviceItem(mDevice);
                        }
                        startLive();
                        startPlayback();
                        putSettingsInfo();
                    }
                    mDeviceUIHelper.setClickOpenDeviceBtn(false);
                }else if (command == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_PTZ_COMMAND){
                    setPtzControlViewClickable(true);
                    Activity activity = TGApplicationBase.getAppLifecycleCallbacks().getCurrentActivity();
                    if (activity instanceof CameraViewActivity){
                        TGToast.showToast(R.string.txt_gimbal_calibration_succeeded);
                    }
                } else if (command == AVIOCTRLDEFs.TCI_CMD_SET_LIGHT_REQ){
                    if (DeviceHelper.isLamp(mDevice)){
                        TGToast.showToast(result == 0? R.string.device_name_changed_success : R.string.device_name_changed_failure);
                    }
                }

            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_WIFI_SIGNALLEVEL_RESP) {
                int activeNetIntf = Packet.byteArrayToInt_Little(data, 0);//0:有线;1-Wifi;2-4G
                int signalLevel = Packet.byteArrayToInt_Little(data, 4);
                mPlayerView.updateSignalLevel(activeNetIntf, signalLevel);
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_BATTERY_STATUS_RESP) {
                int batteryMode = Packet.byteArrayToInt_Little(data, 0);
                int batteryPower = Packet.byteArrayToInt_Little(data, 4);
                int batteryLow = 0;
                if (data.length >= 12){
                    batteryLow = Packet.byteArrayToInt_Little(data, 8);
                }
                if (isPlayStatusInfo) {
                    mPlayerView.updateBatteryTextStatus(batteryPower, batteryMode);
                }
                mPlayerView.updateBatteryImageStatus(batteryPower, batteryMode, batteryLow);

            }
        });
    }



    private void setDeviceClose() {
        mDevice.is_open = DeviceStateConstants.DEVICE_OFF;
        mPlayerView.setPlayerStatus(CameraPlayerStatusView.STATUS_ERROR_DEVICE_OFF);
        mPlayerView.setBackgroud();
        setLiveClicked(false);
        if (playType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD && mPlayBackFragment != null && mPlayBackFragment.isVisible()) {
            mPlayBackFragment.setPlaybackOff();
        }
    }

    private void onMuteOnClickImpl(){
        isMuteOn = !isMuteOn;
        mPlayerView.setMuteOn(isMuteOn);

        if (mCamera != null) {
            PreferenceUtil.setBoolean(getBaseContext(), mCamera.deviceId + CommonConstants.EXT_MUTE_ON, isMuteOn);
            if (isMuteOn) {
                mCamera.stopAudio();
            } else {
                mCamera.startAudio();
            }
        }
    }

    @Override
    public void onMuteOnClick() {
        if (!isMicrophoneClose()) {
            onMuteOnClickImpl();
        } else if (deviceSettingsInfo.microphoneOn == 0 && mDeviceFeature != null && !StringUtils.isEmpty(mDeviceFeature.microphoneInfo)){
            new TGAlertDialog(this).builder().setTitle(getString(R.string.dialog_microphone_close_title)).setMessage(R.string.dialog_microphone_close_content)
                    .setPositiveButton(getString(R.string.sure), v -> {
                    }).show();
        } else {
            onMuteOnClickImpl();
        }
        reToolbarHide();
        uploadLog("mute");
    }

    private void closeMicrophone(){

    }
    @Override
    public void onReconnectClick() {
        uploadLog("reconnect");
        reConnected = false;
        connect();
        reConnectedCount = 0;
        isPlayToobarShow = false;

    }

    @Override
    public void onScreenCapClick() {
        uploadLog("screen_cap");
    }

    @Override
    public void onDeviceOpenClick() {
        if (mCamera != null && !mCamera.isShared) {
            mCamera.setCloseCMD(DeviceStateConstants.DEVICE_OPEN);
        }
        mPlayerView.mediaSyncStart();
        uploadLog("device_open");
    }

    @Override
    public void onOpenServe() {
        DeviceHelper.openServe(mDevice, this);
    }

    public void onSelectResolutionClick(String text) {
        mPlayerView.onSelectResolutionClick(text, -1);
        setFlContainerVisibility();
    }

    public void onSelectSpeedClick(String text) {
        mPlayerView.onSelectSpeedClick(text);
        setFlContainerVisibility();
    }

    private void createResolutionSheetDialogHelper(List<String> list, int index) {
        CameraBottomSheetDialogHelper.createResolutionSheetDialogHelper(getBottomSheetDialogHelper(), list, index, (action, text, position) -> {
            if (action == BottomSheetListDialog.ACTION_RESOLUTION) {
                mPlayerView.onSelectResolutionClick(text, position);
            }
        });
    }

    @Override
    public void onShowResolution(List<String> list) {
        TGLog.d("EVENT_PLAY_TOOBAR_HIDE5");
        if (AppUtil.isLandscape(CameraViewActivity.this)) {
            if (mLiveViewFragment == null) {
                ViewGroup.LayoutParams layoutParams = relCameraView.getLayoutParams();
                showLiveFragment(layoutParams, false);
            }
            adjustFullScreenView(false);
            if (mLiveViewFragment != null) {
                mLiveViewFragment.adjustInfoView(false, false, true);
                mLiveViewFragment.setResolutionInfo(list);
            }
            setFlContainerVisibility();
            TGApplicationBase.getInstance().putGlobalObject(BottomSheetListDialog.ACTION_RESOLUTION, mFlContainer.getVisibility() == View.VISIBLE);
        } else {
            TGApplicationBase.getInstance().removeGlobalObject(BottomSheetListDialog.ACTION_RESOLUTION);
            createResolutionSheetDialogHelper(list, mPlayerView.getIndex());
        }
    }


    @Override
    public void onPtzControlClick() {
        if (isLandscape) {
            if (mLiveViewFragment == null) {
                ViewGroup.LayoutParams layoutParams = relCameraView.getLayoutParams();
                showLiveFragment(layoutParams, false);
            }
            adjustFullScreenView(false);
            if (mLiveViewFragment != null) {
                mLiveViewFragment.adjustInfoView(false, true, false);
            }
            setFlContainerVisibility();
        } else {
            PtzControlDialog ptzControlDialog = new PtzControlDialog(this, ptzControlTouchListener);
            ptzControlDialog.setCancelable(true);
            ptzControlDialog.setCanceledOnTouchOutside(true);
            ptzControlDialog.setOnDismissListener(dialog1 -> {
                TGLog.d(TAG, "[showCollisionSensingSettings] on dismiss !");
                if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)){
                    setToolbarVisibility(View.VISIBLE);
                    mPlayerView.setToolbarVisibilityImpl(View.VISIBLE);
                    TGLog.d("isPlayToobarShow ==== " + isPlayToobarShow);
                    isPlayToobarShow = true;
                    reToolbarHide();
                }
            });
            ptzControlDialog.show();
        }
    }

    private void setFlContainerVisibility() {
        if (mFlContainer.getVisibility() == View.VISIBLE) {
            mFlContainer.setVisibility(View.GONE);
        } else {
            mFlContainer.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onShowSpeed(List<String> list) {
        if (AppUtil.isLandscape(CameraViewActivity.this)) {
            TGLog.d("EVENT_PLAY_TOOBAR_HIDE5");
            if (mDeviceUIHelper.getPlaybackDisplay() != PLAY_MODE_REALTIME) {
                int pType = CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD;
                if (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_BACK_SDCARD) {
                    pType = CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD;
                }
                if (mPlayBackFragment == null) {
                    ViewGroup.LayoutParams layoutParams = relCameraView.getLayoutParams();
                    showPlaybackFragment(layoutParams, mDeviceUIHelper.getPlaybackDisplay(), pType, false);
                }
                adjustFullScreenView(true);
                showFullSrccenPlayBackControl(false);
                mPlayBackFragment.setLayoutShow(false, true);

            }

            setFlContainerVisibility();
        } else {
            createSpeedSheetDialogHelper(list);
        }

    }


    private void createSpeedSheetDialogHelper(List<String> list) {
        CameraBottomSheetDialogHelper.createSpeedSheetDialogHelper(getBottomSheetDialogHelper(), list, (action, text, position) -> {
            switch (action) {
                case BottomSheetListDialog.ACTION_SPEED_X:
                    onSpeedClick(Integer.parseInt(CameraPlayerToolbarView.SPEED_1));
                    break;
                case BottomSheetListDialog.ACTION_SPEED_2X:
                    onSpeedClick(Integer.parseInt(CameraPlayerToolbarView.SPEED_2));
                    break;
                case BottomSheetListDialog.ACTION_SPEED_4X:
                    onSpeedClick(Integer.parseInt(CameraPlayerToolbarView.SPEED_4));
                    break;
                case BottomSheetListDialog.ACTION_SPEED_8X:
                    onSpeedClick(Integer.parseInt(CameraPlayerToolbarView.SPEED_8));
                    break;
            }
        });
    }

    private BottomSheetListDialog getBottomSheetDialogHelper() {
        if (bottomSheetListDialog == null) {
            bottomSheetListDialog = new BottomSheetListDialog(this);
            bottomSheetListDialog.setCanceledOnTouchOutside(true);
            bottomSheetListDialog.setCancelable(true);
        }
        return bottomSheetListDialog;
    }

    @Override
    public void onPlayBackControlClick() {
        if (mDeviceUIHelper.getPlaybackDisplay() != PLAY_MODE_REALTIME) {
            int pType = CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD;
            if (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_BACK_SDCARD) {
                pType = CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD;
            }
            if (mPlayBackFragment == null) {
                ViewGroup.LayoutParams layoutParams = relCameraView.getLayoutParams();
                showPlaybackFragment(layoutParams, mDeviceUIHelper.getPlaybackDisplay(), pType, false);
            }
            mPlayBackFragment.setLayoutShow(true, false);
            adjustFullScreenView(true);
            showFullSrccenPlayBackControl(false);
        }
        setFlContainerVisibility();
    }

    private void showFullSrccenPlayBackControl(boolean show) {
        if (mPlayBackFragment != null) {
            mPlayBackFragment.showPlaybackControl(show);
        }
    }

    @Override
    public void onLensesChanged(int type, boolean isClicked) {
        float lenses = type;

        if (DeviceFeatureHelper.is2LensesCapZoom(mDeviceFeature)) {
            DeviceFeature.ZoomFeature zoomFeature = mDeviceFeature.getZoomFeature(0);
            String zoom = CommonConstants.PRE_LENSES_CAP_ZOOM_FAR;
            if (LensesConstants.isNear(type)) {
                zoom = CommonConstants.PRE_LENSES_CAP_ZOOM_NEAR;
            }
            String near = String.format("%s_%s", zoom, mDevice.uuid);
            lenses = PreferenceUtil.getFloat(this, near, type);
            if (!isZoomBarChanged && !isClicked) {
                isClicked = true;
                isZoomBarChanged = false;
            }
            if (zoomFeature != null && isClicked) {
                boolean isAnalogZoom = false;
                if (LensesConstants.isNear(type) && zoomFeature.startAnalogZoom) {
                    lenses = 0;
                    isAnalogZoom = true;
                } else if (LensesConstants.isFar(type) && zoomFeature.endAnalogZoom) {
                    lenses = zoomFeature.zoomDivider;
                    isAnalogZoom = true;
                }
                if (isAnalogZoom) {
                    analogZoom(lenses, 1, true, 0, ZOOM_DEFAULT);
                }
            }
        }

        if (LensesConstants.isNear(type)) {
            uploadLog("lenses_near");
        } else {
            uploadLog("lenses_far");
        }
        TGLog.i(TAG, "lenses >>>> " + lenses);

        updateZoomLensesUISave(lenses, 0);


        if (mCamera != null) {
            mCamera.set2LensesCmd(lenses);
        }
        reToolbarHide();
    }

    private void updateZoomLensesUISave(float lenses, int channel) {
        TGLog.d(ZoomView.TAG, "deviceSettingsInfo.zoomPos = " + lenses);
        mPlayerView.updateZoomLenses(lenses, channel);
        if (channel == 0){
            deviceSettingsInfo.zoomPos = lenses;
            mDeviceFeature.zoomPos = lenses;
        }else{
            deviceSettingsInfo.zoomPos2 = lenses;
            mDeviceFeature.zoomPos2 = lenses;
        }

        putSettingsInfo();
    }


    @Override
    public void onSpeedClick(int speed) {
        setSpeed(speed);
        uploadLog("speed");
    }

    @Override
    public void onResolutionChanged(int ch, int resolution) {
        channel = ch;
        TGLog.d("EVENT_PLAY_TOOBAR_HIDE5 onResolutionChanged");
        setStreamCtrlCMD(resolution, ch);
        mHandler.sendEmptyMessageDelayed(EVENT_PLAY_TOOBAR_HIDE, HIDE_TIME);
        uploadLog("resolution");
    }


    @Override
    public void onScreenShotResult(boolean succeed) {
        reToolbarHide();
        if (succeed) {
            showToast(R.string.picture_saved_successfully);
            mHandler.sendEmptyMessageDelayed(EVENT_THUMB_HIDE, 3000);
        } else {
            showToast(R.string.picture_saved_failed);
        }
        uploadLog("screen_shot");
    }


    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    public void onScreenFullClick() {
        reToolbarHide();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        uploadLog("screen_full");
    }

    @Override
    public void onSwitchPlayer(int currentPlayer, boolean cmd) {
        if (mIsPlayBackRunning || !mCamera.isRunningLiveVideo()) return;
        TGLog.d(ZoomView.TAG, "onSwitchPlayer setMultiChannelsStreamCtrl " + currentPlayer + " " + JSON.toJSONString(cmd));
        uploadLog("switch_player");

        // 记录画中画里用户当前选择的画面
        if (mDevice != null) {
            MultiPlayerHelper.writeChannel(this, mDevice.uuid, currentPlayer);
        }

        if (cmd) {
            setMultiChannelsStreamCtrl(currentPlayer);
        }
        if (mCamera != null) {
            mCamera.setPrimaryViewCmd(currentPlayer);
        }
        putSettingsInfo();
    }


    private boolean isLocalStreamMax() {
        return deviceSettingsInfo != null && deviceSettingsInfo.quality != AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
    }

    public void setMultiChannelsStreamCtrl(int current) {
        TGLog.i(TAG, "setMultiChannelsStreamCtrl = " + current + ", isEqu = ");
        boolean isMini = current == CameraPlayerView.PLAYER_ID_MINI;
        int c = isMini? CameraPlayerView.PLAYER_ID_MAIN : CameraPlayerView.PLAYER_ID_MINI;
        int stream = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
        if (deviceSettingsInfo != null){
            stream = (c == 0)? deviceSettingsInfo.quality : deviceSettingsInfo.quality2;
        }

        if (stream == 0){
            stream = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
            cmdHelper.setStreamCtrlCMD(c, stream);
        }else{
            setStreamCtrlCMD(stream, c);
        }

        channel = current;
        TGLog.i(TAG, "setMultiChannelsStreamCtrl channel = " + channel);


        stream = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
        if (deviceSettingsInfo != null){
            stream = (current == 0)? deviceSettingsInfo.quality : deviceSettingsInfo.quality2;
        }
        if (stream == 0){
            stream = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
            cmdHelper.setStreamCtrlCMD(current, stream);
        }else{
            setStreamCtrlCMD(stream, current);
        }

    }

    public void setMultiChannelsStreamCtrl() {
        setMultiChannelsStreamCtrl(channel);
    }


    @Override
    public void onWifiSettings() {
        boolean isOff = PreferenceUtil.getBoolean(this, CommonConstants.PRE_WIFI_SETTINGS_TIPS_OFF);
        if (!isOff) {
            showSettingWifiDialog();
        } else {
            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        }
    }

    @Override
    public void onShowBar() {
        TGLog.d("EVENT_PLAY_TOOBAR_HIDE14");
        mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
    }


    @Override
    public void onMicphoneLandClick() {
        if (mPlayBackFragment != null) {
            ViewGroup.LayoutParams layoutParams = relCameraView.getLayoutParams();
            showLiveFragment(layoutParams, false);
            adjustFullScreenView(false);
        }

        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mFlContainer.getLayoutParams();
        params.width = (int) getResources().getDimension(R.dimen.camera_live_speaking_land);
        mFlContainer.setLayoutParams(params);
        setFlContainerVisibility();
        if (mLiveViewFragment != null) {
            mLiveViewFragment.adjustInfoView(true, false, false);
        }
    }

    @Override
    public void onScreenClick() {
        TGLog.i(TAG, "onScreenClick");
        requestDeviceSleep();
        setContainerGone();
    }

    @Override
    public void onHelpClick(boolean isbad) {
        String url = TGGlobalConfigHelper.getInstance().getHelpUrl(mDevice, isbad);
        if (!TextUtils.isEmpty(url)) {
            UriUtil.openServePlay(this, url, deviceSettingsInfo, 0);
        }
    }


    private void setContainerGone() {
        mHandler.post(() -> {
            if (isLandscape && mFlContainer.getVisibility() == View.VISIBLE) {
                TGApplicationBase.getInstance().putGlobalObject(BottomSheetListDialog.ACTION_RESOLUTION, false);
                mFlContainer.setVisibility(View.GONE);
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        TGLog.i(TAG, "onActivityResult requestCode = " + requestCode + " , resultCode = " + resultCode);


        if (resultCode == SleepLockActivity.RESULTOK) {
            isPlayToobarShow = false;
            return;
        }
        if (isLiveFragmentVisiable()) {
            mLiveViewFragment.onActivityResult(requestCode, resultCode, data);
        }
        if (isPlaybackFragmentVisible()) {
            mPlayBackFragment.onActivityResult(requestCode, resultCode, data);
        }
        if (resultCode == RESULT_OK) {
            if (data != null) {
                DeviceItem deviceItem = data.getParcelableExtra(CommonConstants.EXT_DEVICE_ITEM);
                if (deviceItem != null) {
                    TGLog.d(DeviceSettingsActivity.TAG, "ispen1==" + deviceItem.is_open);
                    mDevice = deviceItem;
                }
            }
        }
        getServiceInfo();
    }

    public int getContainerHeight() {
        return mFlContainer.getHeight();
    }


    @Override
    public void onShowNav(boolean isClick) {
        setToolbarVisibility(View.VISIBLE);
        TGLog.d("EVENT_PLAY_TOOBAR_HIDE3");
        mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
        if (isClick) {
            mHandler.sendEmptyMessageDelayed(EVENT_PLAY_TOOBAR_HIDE, HIDE_TIME);
        }
        if (isClick && isLandscape && mFlContainer.getVisibility() == View.VISIBLE) {
            if (!mIsPlayBackRunning) {
                mFlContainer.setVisibility(View.GONE);
            }
        }
    }

    private void setToolbarVisibility(int visibility) {
        if (isToolbarMultiChannelsVisibile() && visibility == GONE) return;
        if (View.VISIBLE == visibility) {
            if (relToolbar.getVisibility() != View.VISIBLE) {
                relToolbar.animate().translationY(0).alpha(1.0f).setDuration(240).setListener(null).start();
                relToolbar.setVisibility(View.VISIBLE);
            }
        } else {
            if (relToolbar.getVisibility() == View.VISIBLE) {
                relToolbar.animate().translationY(-relToolbar.getHeight()).setDuration(240).setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        relToolbar.setVisibility(View.INVISIBLE);
                    }
                }).start();
            } else {
                relToolbar.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public void onZoom(int type, float scale, boolean isSeekbar, int index) {
        isZoomBarChanged = true;
        int x = -1;
        int y = -1;
        reToolbarHide();
        TGLog.d(ZoomView.TAG, "lenses======" + scale + ", type = " + type + ", index = " + index);
        if (mCamera == null) return;
        if (type == ZoomView.CAMERA_ZOOM_TYPE_DEFINE) {
            int sleep = 0;
            float dur = 1;
            if (mDeviceFeature != null ){
                DeviceFeature.ZoomFeature zoomFeature = mDeviceFeature.getZoomFeature(index);
                if (mDeviceFeature.is2LensesCapZoom()){
                    if (zoomFeature.isInEndArea(scale) ^ zoomFeature.isInEndArea(deviceSettingsInfo.zoomPos)) {
                        sleep = 1000;
                    } else {
                        float diff = index == 0? deviceSettingsInfo.zoomPos - scale : deviceSettingsInfo.zoomPos2 - scale;
//                        float div = (zoomFeature.startFactor - 1);
//                        if (zoomFeature.isInEndArea(deviceSettingsInfo.zoomPos)) {
//                            div = (zoomFeature.maxFactor - zoomFeature.startFactor - 1);
//                        }
                        dur = Math.abs(diff);
                    }
                }
                if (zoomFeature.isSingleZoom()){
                    float diff = index == 0? deviceSettingsInfo.zoomPos - scale : deviceSettingsInfo.zoomPos2 - scale;
                    dur = Math.abs(diff);
                }
            }
            TGLog.i(TAG, "onZoom " + sleep);
            updateLensesCapZoom(scale);
            if (index == 0){
                deviceSettingsInfo.zoomPos = scale;
            }else{
                deviceSettingsInfo.zoomPos2 = scale;
            }

            putSettingsInfo();
            TGThreadPool.executeOnUiThreadDelayed(() -> {
                TGLog.d(ZoomView.TAG, "onZoom send lenses======"+scale);
                mCamera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_SET_PTZ_POS_REQ, AVIOCTRLDEFs.Tcis_SetPtzPosReq.parseContent(x, y, scale, index, 1));
            }, sleep);

            TGLog.d(ZoomView.TAG, "onZoom send lscale======"+scale + ", dur = " + dur + ", index = " + index);
            analogZoom(scale, dur, false, index, ZOOM_DEFAULT);
            mPlayerView.updateZoomLenses(scale, index);
        } else if (type == ZoomView.CAMERA_ZOOM_TYPE_UNKOWN) {
            zoomUnkown( scale, 0, 0);
        }

        if (isSeekbar) {
            mPlayerView.hideZoomTextView(index);
            uploadLog("zoom_seekbar");
        } else {
            uploadLog("zoom_button");
        }
    }

    private void zoomUnkown(float scale, int x, int y) {
        int z = (int)scale;
        if (Math.abs(z)==1){
            CameraHelper.sendPTZCMDShort(mCamera, x, y, z, 0, 0);
        }else {
            if (z==0){
                reToolbarHide();
            }else {
                mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
            }
            mCamera.sendPTZCMD(z,channel);
        }
    }

    @Override
    public void onZoomCameraChanged(boolean isFarCamera, float scale, int index) {
        TGLog.d("lenses======" + scale + ", onZoomCameraChanged ");
        updateLensesCapZoom(scale);
        mPlayerView.setLensesChanged();
    }

    private void analogZoom(float scale, float dur, boolean isClick, int index, String from) {
        int duration = (int) (3000 * dur);
        mPlayerView.analogZoom(scale, duration, isClick, index, from);
    }

    @Override
    public void onZoomChangeState(float borderFactor, float progress, int index) {
        mPlayerView.setLensesChanged(progress > borderFactor);
    }

    @Override
    public void onZoomChanging(float scale, int index) {
        TGLog.d("scale = " + scale + ", index = " + index);
        mPlayerView.setZoomTextView(scale + "x", index);
        reToolbarHide();
    }

    private void updateLensesCapZoom(float v) {
        TGLog.d("v======" + v);
        if (mDeviceFeature != null && mDeviceFeature.is2LensesCapZoom() && mDeviceFeature.getZoomFeature(0).zoomDivider > 0) {
            DeviceFeature.ZoomFeature zoomFeature = mDeviceFeature.getZoomFeature(0);
            String zoom = CommonConstants.PRE_LENSES_CAP_ZOOM_NEAR;
            if (zoomFeature.isInEndArea(v)) {
                zoom = CommonConstants.PRE_LENSES_CAP_ZOOM_FAR;
            }
            String far = String.format("%s_%s", zoom, mDevice.uuid);
            TGLog.d("far ==== " + far);
            PreferenceUtil.setFloat(this, far, v);
        }
    }

    private void onPtzShortCmd(int control, boolean isScreen) {
        requestDeviceSleep();
        uploadLog("onShortCmd");
        TGLog.d(PtzControlView.TAG, "onPtzShortCmd = " + control);
        if (mCamera != null && mCamera.isConnected() && !mIsPlayBackRunning) {
            reToolbarHide();
            mHandler.removeMessages(EVENT_SEND_PTZCMD_LONG);
            mCamera.sendPTZCMDShort(control, channel);
            ptzHide();
            mPlayerView.ptzDirection(control, isScreen);
        }

    }


    private void ptzHide() {
        mHandler.removeMessages(EVENT_PTZCMD_HIDE);
        mHandler.sendEmptyMessageDelayed(EVENT_PTZCMD_HIDE, 100);
    }

    private void onPtzStopCmd() {
        requestDeviceSleep();
        if (mCamera != null && mCamera.isConnected()) {
            reToolbarHide();
            mHandler.removeMessages(EVENT_SEND_PTZCMD_LONG);
            TGLog.d(PtzControlView.TAG, "onPtzStopCmd()) ");
            mCamera.sendPTZCMD(AVIOCTRLDEFs.AVIOCTRL_PTZ_STOP, channel);
        }
        ptzHide();
    }

    private void onPtzLongCmd(int control, boolean isScreen) {
        requestDeviceSleep();
        uploadLog("onPtzLongCmd");
        if (mCamera != null && mCamera.isConnected() && !mIsPlayBackRunning) {
            mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
            mHandler.removeMessages(EVENT_PTZCMD_HIDE);
            Message message = mHandler.obtainMessage();
            message.what = EVENT_SEND_PTZCMD_LONG;
            message.arg1 = control;
            //5 毫秒后发
            mHandler.sendMessageDelayed(message, 200);
            mPlayerView.ptzDirection(control, isScreen);
        }

    }

    public void reToolbarHide() {
        TGLog.d("EVENT_PLAY_TOOBAR_HIDE2");
        mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
        mHandler.sendEmptyMessageDelayed(EVENT_PLAY_TOOBAR_HIDE, HIDE_TIME);
    }

    private void uploadLog(String btn) {
        String name = "live";
        if (mIsPlayBackRunning) {
            name = "playback";
        }
        LogUtils.onEventClickByName(name, btn);
    }

    private class DeviceBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            if (action.equals(SocketIoConstants.NOTIFY_DEVICE_STATUS)) {
                TGLog.i(TAG, "DeviceBroadCastReceiver.NOTIFY_DEVICE_STATUS devices status");
                String data = intent.getStringExtra(SocketIoConstants.NOTIFY_KEY_DATA);
                if (TextUtils.isEmpty(data) || mCamera == null) return;
                try {
                    JSONObject object = new JSONObject(data);
                    int deviceId = object.optInt("device_id");
                    //int status = object.optInt("status");

                    if (deviceId == mCamera.deviceId) {
                        String type = object.optString("type");
                        TGLog.i(TAG, "LiveView devices type " + type);
                        if (TextUtils.equals(type, SocketIoConstants.DEVICE_STATUS_SHUTDOWN)) {
                            if (mCamera != null && mCamera.isConnected()) {
                                mCamera.stopAudio();
                                mCamera.stopShow();
                                if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)) {
                                    mCamera.stopShowMini();
                                }
                            }
                            if (mDevice != null) {
                                mDevice.is_open = DeviceStateConstants.DEVICE_OFF;
                                mPlayerView.setBackgroud();
                            }
                        } else if (TextUtils.equals(type, SocketIoConstants.DEVICE_STATUS_OPEN)) {
                            if (mDevice != null) {
                                mDevice.is_open = DeviceStateConstants.DEVICE_OPEN;
                                mPlayerView.setBackgroud();
                            }
                        } else {
                            getPassword();
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (action.equals(CommonConstants.ACTION_INTENT_USER_OFFLINE)) {
                mIsUserOffline = true;
                if (mCamera != null && mCamera.isConnected()) {
                    mCamera.stopAudio();
                    mCamera.stopShow();
                    if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)) {
                        mCamera.stopShowMini();
                    }
                    mCamera.disconnect();
                }
                if (isPlaybackFragmentVisible()) {
                    mPlayBackFragment.onPlaybackPause();
                }
            } else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)){
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_TURNING_ON:
                        TGLog.d("Bluetooth","蓝牙正在打开");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        TGLog.d("Bluetooth","蓝牙已经打开");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        TGLog.d("Bluetooth","蓝牙正在关闭");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        TGLog.d("Bluetooth","蓝牙已经关闭");
                        break;
                }
            } else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)){
                TGLog.d("Bluetooth","蓝牙设备已连接");
                AudioManager audioManager = (AudioManager) TGApplicationBase.getApplication().getSystemService(Context.AUDIO_SERVICE);
                audioManager.setMode(AudioManager.MODE_NORMAL);
                audioManager.setSpeakerphoneOn(false);
            } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)){
                TGLog.d("Bluetooth","蓝牙设备已断开");
                AudioManager audioManager = (AudioManager) TGApplicationBase.getApplication().getSystemService(Context.AUDIO_SERVICE);
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                audioManager.setSpeakerphoneOn(true);
            }
        }
    }

    /**
     * 更新设备访问密码
     */
    private void getPassword() {
        HashMap<String, String> hashMap = new HashMap<>();
        long deviceId = mCamera == null ? 0 : mCamera.deviceId;
        hashMap.put("device_id", String.valueOf(deviceId));
        TGHttp.getInstance().getDevicePassword(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<DeviceItem>() {
                    @Override
                    protected void onSuccess(DeviceItem content) {
                        if (mCamera != null) {
                            mCamera.disableLanSearch(content.password);
                            mCamera.uid = content.uuid;
                            mCamera.reSendPwd();
                        }
                    }
                });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        TGLog.i(TAG, "onTouchEvent");
        return super.onTouchEvent(event);
    }

    private void getDeviceStatusInfo() {
        if (mCamera != null && mCamera.isConnected() && !mIsPlayBackRunning) {
            int userId = PreferenceUtil.getInt(this, CommonConstants.PRE_USER_ID);
            if (mDeviceFeature != null && mDeviceFeature.isBatteryCam && BatteryHelper.showBattery(userId, mCamera.uid)) {
                TGLog.d(" === getDeviceStatusInfo start " );
                mCamera.getBatteryStatusCMD();
            }
            if (isPlayStatusInfo) {
                mCamera.getSignalLevelCMD();
            }
            mHandler.sendEmptyMessageDelayed(EVENT_DEVICE_INFO, 30 * 1000);
        } else {
            mHandler.removeMessages(EVENT_DEVICE_INFO);
            mHandler.sendEmptyMessage(EVENT_DEVICE_INFO_HIDE);
        }
    }

    private void connectedAction() {
        if ((isLiveFragmentVisiable()) || mPlayBackFragment != null && !mIsPlayBackRunning) {
            startLive();
        }
        if (mPlayBackFragment != null) {
            mPlayBackFragment.rePlayCurrentTime();
        }
    }

    private void getServiceInfo() {
        if (mDevice == null || isLocalConnect()) return;

        ServiceInfoHelper.getServiceInfo(mDevice.uuid, new ServiceInfoHelper.ServiceInfoListener<HashMap<String, DeviceServiceStatusBean>>() {
            @Override
            public void onSuccess(HashMap<String, DeviceServiceStatusBean> resp) {
                TGLog.i(TAG, "[query][onSuccess] resp = " + resp);
                if (resp != null){
                    DeviceServiceStatusBean deviceServiceStatusBean = resp.get(mDevice.uuid);
                    if (deviceServiceStatusBean != null){
                        mDevice.server_data = deviceServiceStatusBean.storage;
                        mDevice.sim_server_data = deviceServiceStatusBean.sim;
                        mDevice.car_server_data = deviceServiceStatusBean.car;
                        mDevice.ai_server_data = deviceServiceStatusBean.ai;
                        mDevice.foreignServiceHook = deviceServiceStatusBean.foreign_service_hook;

                        if (deviceServiceStatusBean.ai != null){
                            TGLog.d("PlayBackFragment-log", "deviceServiceStatusBean.ai.level ==== " + deviceServiceStatusBean.ai.level);
                        }

                        mDevice.server_bought.ai_server = deviceServiceStatusBean.bought.ai? 1 : 0;
                        mDevice.server_bought.car_server = deviceServiceStatusBean.bought.car? 1 : 0;
                        mDevice.server_bought.sim_server = deviceServiceStatusBean.bought.sim? 1 : 0;
                        mDevice.server_bought.server = deviceServiceStatusBean.bought.storage? 1 : 0;

                        if (mPlayBackFragment != null) {
                            mPlayBackFragment.setDeviceItem(mDevice);
                        }

                        if (mLiveViewFragment != null){
                            mLiveViewFragment.setDeviceItem(mDevice);
                        }
                        if (DeviceHelper.isCarPrimary(mDevice)) {
                            isCanDo();
                            if (CarWatchTimeHelper.isCarPrimaryWatchEnd(watchTime) || CarWatchTimeHelper.isCarPrimaryWatchExpired(watchTime)) {
                                stopPlayer();
                            } else {
                                getServiceInfoConnect();
                            }
                        } else if (DeviceHelper.hasServe(mDevice)) {
                            getServiceInfoConnect();
                        }
                    }
                }
            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                String msg = "errorCode = " + errorCode + " , errorInfo = " + errorInfo;
                TGLog.i(TAG, "[query][onResponseError] " + msg);
            }
        });
    }

    private void getServiceInfoConnect() {
        mCameraPlayerShowErrorView.setVisibility(GONE);

        if (mCamera != null && !mCamera.isConnected()) {
            connect();
        } else {
            connectedAction();
        }
    }



    protected void settingsClick() {
        uploadLog("settings");
        jumpSettings();
    }

    protected void jumpSettings() {
        if (mCamera != null) {
            mCamera.unregisterICameraListener(this);
            mCamera.unregisterCameraAVListener(this);
            mCamera.setPlaybackListener(null);
            if (isLocalConnect()) {
                CameraHub.getInstance().setEnableLocalApConnect(true);
                if (mDeviceFeature != null && mDeviceFeature.isDriveRec) {
                    mDevice.device_type = DeviceTypeHelper.DEVICE_DRSIM;
                    mCamera.isShared = false;
                }
            }
            ActivityHelper.jump2SettingActivityForResult(CameraViewActivity.this, mDevice, mOrigin);
        }
    }

    private final AppStatusChangeListener mAppStatusChangeListener = (currentActivity, activityNumber, status) -> {
        TGLog.d("status = " + status + ", activityNumber" + activityNumber);
        if (activityNumber == 0 && status == STATUS.STATUS_BACKGROUND) {
            TGApplicationBase.getInstance().setBackgroundTime();
        } else if (status == STATUS.STATUS_FOREGROUND && currentActivity instanceof CameraViewActivity) {
            ActivityHelper.goToDeviceListActivity(CameraViewActivity.this);
        }else if (status== STATUS.STATUS_BACKGROUND_TIMER && DeviceHelper.isBatteryDevice(mDevice)){
            if (mCamera!=null){
                mCamera.disconnect();
            }
        }
    };

    public boolean isSupportPresetPointNotMultiChannels() {
        return mDeviceFeature != null && mDeviceFeature.presetPos;
    }

    public boolean isSupportCruise(){
        return mDeviceFeature != null && mDeviceFeature.cruise;
    }
    public boolean isSupportWatchPos() {
        return DeviceFeatureHelper.supportWatchPos(mDeviceFeature);
    }

    public boolean isSupportPTZReset(){
        return DeviceFeatureHelper.supportPTZ(mDeviceFeature) && DeviceFeatureHelper.parseReset(mDeviceFeature);
    }

    private boolean isMoreSettingsIcon(){
        if (isSupportPresetPointNotMultiChannels() && !DeviceHelper.isCar(mDevice) && !StringUtils.equalsIgnoreCase(TGConfig.APP_ID, TGConfig.APP_ID_HSAB) && !isSupportCruise()) {
            return true;
        }

        return DeviceFeatureHelper.supportPTZ(mDeviceFeature) && DeviceFeatureHelper.parseReset(mDeviceFeature) && !StringUtils.equalsIgnoreCase(TGConfig.APP_ID, TGConfig.APP_ID_HSAB);
    }

    protected void showSettingsBottomSheet() {
        List<BottomSheetListDialog.BottomSheetItem> bottomSheetItems = new ArrayList<>();
        bottomSheetItems.add(new BottomSheetListDialog.BottomSheetItem(BottomSheetListDialog.ACTION_SETTINGS, 0, getResources().getString(R.string.device_function_settings)));
        boolean isShow = isSupportPresetPointNotMultiChannels() && !mIsPlayBackRunning;
        if (isShow && !StringUtils.equalsIgnoreCase(TGConfig.APP_ID, TGConfig.APP_ID_HSAB) && !isSupportCruise()) {
            bottomSheetItems.add(new BottomSheetListDialog.BottomSheetItem(BottomSheetListDialog.ACTION_PRE_POSITION, 0, getResources().getString(R.string.bottom_sheet_pre_position)));
        }

        if (DeviceFeatureHelper.supportPTZ(mDeviceFeature) && DeviceFeatureHelper.parseReset(mDeviceFeature) && !StringUtils.equalsIgnoreCase(TGConfig.APP_ID, TGConfig.APP_ID_HSAB)){
            bottomSheetItems.add(new BottomSheetListDialog.BottomSheetItem(BottomSheetListDialog.ACTION_DIALOG_PTZ, 0, getResources().getString(R.string.txt_optimizatio_ptz)));
        }
        CameraBottomSheetDialogHelper.showSettingsBottomSheet(getBottomSheetDialogHelper(), bottomSheetItems, (action, text, position) -> {
            switch (action) {
                case BottomSheetListDialog.ACTION_PRE_POSITION:
                    showPrePosition();
                    if (mCamera != null && mCamera.isConnected()) {
                        mHandler.removeMessages(EVENT_PLAY_TOOBAR_HIDE);
                        setToolbarVisibility(View.INVISIBLE);
                        mPlayerView.setToolbarVisibility(View.INVISIBLE);
                    }
                    break;
                case BottomSheetListDialog.ACTION_DIALOG_PTZ:
                    showPTZOptimization();
                    break;
                case BottomSheetListDialog.ACTION_SETTINGS:
                    jumpSettings();
                    break;
            }
        });
    }

    private void setPtzControlViewClickable(boolean clickable){
        if (mLiveViewFragment instanceof CameraLiveFragment){
            ((CameraLiveFragment)mLiveViewFragment).setPtzControlViewClickable(clickable);
        }
    }
    public void showPTZOptimization(){
        if (mCamera != null && !mCamera.isConnected()) {
            showToast(R.string.live_offline);
        }else{
            assert mCamera != null;
            mCamera.sendPTZCMD(AVIOCTRLDEFs.TCIC_MOTOR_RESET_POSITION, 0);
            TGToast.showToast(R.string.txt_camera_needs_seconds);
            setPtzControlViewClickable(false);

            TGThreadPool.executeOnUiThreadDelayed(() -> setPtzControlViewClickable(true), 20000);
        }

    }

    private void showPrePosition() {
        prePositionHelper = new PrePositionDialog(this, mDeviceFeature, dialog -> {
            if (mCamera != null) {
                mCamera.registerICameraListener(CameraViewActivity.this);
                mCamera.unregisterICameraListener(prePositionHelper);
            }

            TGApplicationBase.getInstance().removeGlobalObject(PrePositionDialogAdapter.TAG);
            prePositionHelper = null;
        });
        prePositionHelper.setOnPtzControlTouchListener(ptzControlTouchListener);
        prePositionHelper.setCamera(mCamera);
        prePositionHelper.show();
    }
}